Save Canvas with Background Image

10,048

Solution 1

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.

Solution 2

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
Share:
10,048
Akash
Author by

Akash

Tell me and i forget. Teach me and i remember. Involve me and i learn. - Benjamin Franklin

Updated on June 15, 2022

Comments

  • Akash
    Akash almost 2 years

    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?

  • anam
    anam over 10 years
    can you plz explain more ?? i need this functionality
  • Jose Manuel Abarca Rodríguez
    Jose Manuel Abarca Rodríguez almost 5 years
    I get an error in "myCanvas.canvas.toDataURL" : the "canvas" is undefined.
  • Jose Manuel Abarca Rodríguez
    Jose Manuel Abarca Rodríguez almost 5 years
    Simon, would explain your idea just a little bit? We really need it :)