2019-02-13JavaScript将Canvas内容转化成图片

将图片放入画布里,我们使用canvas元素的drawImage方法:

// Converts image to canvas; returns new canvas element
function convertImageToCanvas(image) {
    var canvas = document.createElement("canvas");
    canvas.width = image.width;
    canvas.height = image.height;
    canvas.getContext("2d").drawImage(image, 0, 0);

    return canvas;
}

这里的0, 0参数画布上的坐标点,图片将会拷贝到这个地方。
将canvas数据转换成图片格式:

// Converts canvas to an image
function convertCanvasToImage(canvas) {
    var image = new Image();
    image.src = canvas.toDataURL("image/png");
    return image;
}

注意:
//如果没有这一段代码保存图片你会想死
img.setAttribute("crossOrigin",'Anonymous');

function draw(){ 
            var img = new Image();          
            img.src = "https://pic2.zhimg.com/v2-3f3533b2e479e2a17cc96654024a8b41_r.jpg";
            img.setAttribute("crossOrigin",'Anonymous');
            var canvas = document.getElementById("thecanvas");  
            var ctx = canvas.getContext("2d");          
            // 绘制水印一下内容可自行更改,建议使用一种颜色
            img.onload = function(){
                ctx.drawImage(img,0,0);
                ctx.font="20px microsoft yahei";
                ctx.fillStyle = "red(255,255,255,0.5)";
                ctx.fillText("my images",100,100);
                ctx.fillText("my images",100,150);
                ctx.fillText("my images",100,200);
                ctx.fillText("my images",100,250);
                }
            }

你可能感兴趣的:(2019-02-13JavaScript将Canvas内容转化成图片)