6

I have a background image for a canvas, and added a few basic elements to the canvas. Now I want to save the canvas (in .png), with the background image of the canvas style.

Tried:

var canvas = document.getElementById("mycanvas");
var img    = canvas.toDataURL("image/png");

But this doesn't seem to save the background image of the canvas. Is there a way out?

mhlester
  • 22,781
  • 10
  • 52
  • 75
Akash
  • 4,956
  • 11
  • 42
  • 70

2 Answers2

6

When you want to save the Canvas + background as an image, you will need to do a sequence of events:

  1. Create an in-memory canvas just as big as your normal canvas. Call it can2
  2. ctx2.drawImage(can1, 0, 0) // paint first canvas onto new canvas
  3. ctx.clearRect(0, 0, width, height) // clear first canvas
  4. ctx.drawImage(background, 0, 0) // draw image on first canvas
  5. ctx.drawImage(can2, 0, 0) // draw the (saved) first canvas back to itself
Simon Sarris
  • 62,212
  • 13
  • 141
  • 171
4

To save an image location, I believe your looking for:

window.location = canvas.canvas.toDataURL('image/png');

The first canvas call is your variable the second is the canvas object. You should probably rename your variable to something unique.

To set an image in canvas and make that the background requires some more work:

var myCanvas = document.querySelector('myCanvas'),     
    img = document.createElement('img'),    
    ctx = myCanvas.getContext ? myCanvas.getContext('2d') : null;

    myCanvas.width = window.innerWidth;
    myCanvas.height = window.innerHeight;
    img.onload = function () {  
        ctx.drawImage(img, 0, 0, myCanvas.width, myCanvas.height);
    };
img.src = 'image.png';

updated to redraw the image.

Andre Dublin
  • 1,148
  • 1
  • 16
  • 34