Save HTML5 canvas contents, including dragged-upon images

£可爱£侵袭症+ 提交于 2019-12-10 11:56:24

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/7127263/save-html5-canvas-contents-including-dragged-upon-images

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!