2

I have a canvas element that I'm setting the background on dynamically via code. Then I'm using the Sketch library (http://intridea.github.io/sketch.js/) to draw on the canvas. - This all works.

However, whenever I try to convert the canvas using canvas.toDataURL("image/png") it's able to save the canvas drawing, however isn't saving the background. - I understand this is working as designed.

Is there a way to merge the two? I was toying around with the idea that I could set the image src to the background src after I'm done drawing and try to export that, however I'm not certain. Does anyone have any experience with this?

3 Answers3

2

As you've discovered, the canvas and its background are maintained separately and toDataURL will not also capture the background.

You can combine the background with the sketch using canvas compositing.

The 'destination-over' compositing mode will let you drawImage your background behind the sketches

context.globalCompositeOperation="destination-over";

context.drawImage(backgroundImage,0,0);

Now the background pixels have been drawn behind you sketch and both will be captured with toDataURL.

markE
  • 102,905
  • 11
  • 164
  • 176
2

Yes, You are correct. I fetch the background image along with canvas image and download.

 ctx.width = 2503;
    ctx.height = 250;
    ctx.globalCompositeOperation="destination-over";
    var background = new Image();
    background.src = "http://localhost/xxxxx/xxxxx/xxxxx/xxxxx/ecg_back.png";   
    ctx.drawImage(background, 0, 0);
    // create pattern
    var ptrn = ctx.createPattern(background, 'repeat'); // Create a pattern with this image, and set it to "repeat".
    ctx.fillStyle = ptrn;
    ctx.fillRect(0, 0, ctx.width, ctx.height);
peeebeee
  • 2,541
  • 6
  • 21
  • 26
Kathirvel
  • 31
  • 2
0

How are you adding the background to the canvas? Are you setting it in css as a background image? Or are you adding the image directly to the canvas? I think you'll need to do the latter, as per the example here.

Community
  • 1
  • 1
Tom McQuarrie
  • 1,087
  • 9
  • 16
  • I'm setting it via jQuery background url attribute. EDIT: I've tried to follow that example, however when I click to begin drawing on the image, it clears the image out and begins drawing, that's what cause me to go to the background url route. – Shawn Christopher Apr 10 '14 at 13:23