如何将HTML5画布保存到png [英] How to save an HTML5 canvas to a png
问题描述
我正在尝试将画布另存为图像,以便可以将其作为标签放置在网站上的其他位置。
我见过这样的方法:
I am trying to have a canvas be saved as an image so it can be put somewhere else on the website as an tag. I have seen approaches like this:
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var strDataURI = canvas.toDataURL("image/png;base64");
document.write('<img src="'+strDataURI+'"/>');
但是我不确定如何实现它。我也希望将图像的副本也保存为服务器上的实际文件,但是我不确定从哪里开始。
But I am not sure how to implement it. I also would like a copy of the image to be saved as an actual file on the server as well but I am not sure where to start.
当我实现上述内容时代码,我将其放在画布脚本的底部,例如:
When I implement the above code, I put it at the bottom of my canvas script like such:
var finish = document.getElementID('finish');
finish.onclick = function() {
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var strDataURI = canvas.toDataURL("image/png;base64");
};
但是我不知道如何实际引用图像。
我需要为noob提供一点帮助。
But I don't know how to actually reference the image. A little help for noob is all I need.
推荐答案
在前端,这里有一个完整的工作示例,仅显示了一个红色背景。
http://jsfiddle.net/gramhwkg/
For the frontside here's a full working example only showing a red background. http://jsfiddle.net/gramhwkg/
// create a canvas
// If the canvas is already a dom element
//var canvas = document.getElementById("canvas");
// otherwise you'd rather do
var canvas = document.createElement('canvas');
// Then set a width/height grab its context.
canvas.width = 900;
canvas.height = 400;
var ctx = canvas.getContext("2d");
// ... And do plenty of nice stuff with it.
// I'll just draw it Red.
ctx.fillStyle = "#FF0000";
ctx.fillRect(0,0,900,400);
// When you want it to appear elsewhere.
var data = canvas.toDataURL();
var picture = document.getElementById("my-picture");
picture.innerHTML = '<img src="' + data + '"/>' ;
后端部分并不难。只需POST到php相同的图像数据变量并以这种方式处理它即可:
The backend part is not much harder. Just POST to php the same image data variable and handle it that way :
$canvas = base64_decode(str_replace('data:image/png;base64,', '' , $value['picture']));
file_put_contents('my_custom_path/my_custom_filename.png', $canvas);
希望这会有所帮助!
这篇关于如何将HTML5画布保存到png的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!