0

I'm using a canvas to load a background image, and then, using jQuery UI, I call the droppable() function on the canvas and draggable() on a bunch of PNG images on the screen (that are not in the canvas). After the user drags one or more images on the canvas, I allow him to save the contents to a file using the following function:

function saveCanvas() {
    var data = canvas.toDataURL("image/png");
    if (!window.open(data)) {
        document.location.href = data;
    }
}

This successfully open another window with an image, that sadly contains only the original background image, not the dragged images. I'd like to save an image presenting the final stage of the canvas. What am I missing here?

Thanks for your time.

Traveling Tech Guy
  • 27,194
  • 23
  • 111
  • 159
  • Are the images being dragged on all located in the same place as the HTML file where your canvas element is? – robertc Aug 20 '11 at 01:21
  • Yes @robertc, they are on the same folder, under the same root, just in a different directory - otherwise I run into a security error (cross-domain content). That is not my issue. – Traveling Tech Guy Aug 20 '11 at 03:18

2 Answers2

3

You've got to draw the images to the canvas.

Here is a live example:

http://jsfiddle.net/6YV88/244/

To try it out, drag the kitten and drop it somewhere over the canvas (which is the square above the kitten). Then move the kitten again to see that it's been drawn into the canvas.

The example is just to show how an image would be drawn into the canvas. In your app, you wouldn't use the draggable stop method. Rather, at save time you would iterate through the pngs, drawing them on to your canvas. Note that the jQuery offset() method is used to determine the positions of the canvas and images relative to the document.

brainjam
  • 18,863
  • 8
  • 57
  • 82
0

You are saving the final state of the canvas. You have images atop the canvas and the canvas has zero knowledge of them.

The only way you can save the resulting thing you see is to, before you call toDataUrl, you must call ctx.drawImage with each of the images and actually draw them to the canvas.

Getting the right coordinates for the call to drawImage might get tricky but its not impossible. You'll have to use the pageX and pageY coordinates of the image, probably, and then draw them onto the canvas relative to the canvas' own pageX and pageY.

Simon Sarris
  • 62,212
  • 13
  • 141
  • 171