保存画布与背景图像(Saving Canvas with the background image)

2019-10-17 19:25发布

我有一个背景图像的HTML5 canvas元素。 用户可以绘制图像,然后需要将完整的canvas元素保存与背景。 我使用下面的代码保存部分,但它只是变得画布绘制,但不是背景图像。 我能做得到的背景图像也?

var canvas = document.getElementById('your_canvas');
             var context = canvas.getContext('2d');
             // save canvas image as data url (png format by default)
             var dataURL = canvas.toDataURL();

             // set canvasImg image src to dataURL
             // so it can be saved as an image
             document.getElementById('canvasImg').src = dataURL;

更新:

我的HTML

<div name='coords1' class='canvas-area input-xxlarge' disabled
placeholder='Shape Coordinates' id='imgDiv'
data-image-url='BackGround.jpg'></div>

我在我的HTML网页上面的DIV。 然后我动态创建的画布,画就可以了。 这是一个有点冗长的代码。

Answer 1:

不要在使用图像div ,绘制的图像canvas ..

使用下面的代码在画布上绘制图像,

var img=new Image();
img.src=/*image src*/;
var ctx=canvas.getContext("2d");
img.onload=function()
{
    ctx.drawImage(img,x,y,width,height);
}

在图像绘制完成后img.onload回调,允许用户在画布上绘制...

现在保存画布绘制....



Answer 2:

要获得backgound图像画布

context.globalCompositeOperation="destination-over";
drawImage(yourBackgroundImage,0,0);


文章来源: Saving Canvas with the background image