Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save Canvas with Background Image

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?

like image 906
Akash Avatar asked Aug 05 '11 13:08

Akash


People also ask

Can canvas have a background image?

There are two ways available in FabricJS, using which we can change the background image of the canvas. First method is by using the Canvas class itself and passing backgroundImage in the second parameter of the class. Second method is to use the setBackgroundColor method. Let's see into each of them with an example.

How do I get canvas toDataURL?

Here is the code to do that: var canvas = document. getElementById("ex1"); var dataUrl = canvas. toDataURL(); window.


2 Answers

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
like image 164
Simon Sarris Avatar answered Sep 19 '22 03:09

Simon Sarris


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.

like image 43
Andre Dublin Avatar answered Sep 21 '22 03:09

Andre Dublin