简体   繁体   中英

Saving Canvas with the background image

I have a HTML5 canvas element with a background image. User is allowed to draw on the image and then need to save the complete canvas element with the background. I'm using below code for saving part but it only gets the canvas drawing but not the background image. what could i do to get the background image also?

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;

Update:

My HTML

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

I have the above div in my HTML page. then i dynamically create the canvas and draw on it. It's a bit lengthy code.

Don't use image on the div , draw the image on the canvas ..

use the following code to draw image on canvas,

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

After image drawing completion at img.onload callback , allow user to draw on canvas...

Now save the canvas drawing....

To Get the Canvas with backgound Image

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM