javascript HTML5 画布,保存 jpeg blob 并从 blob 恢复到画布
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18419246/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HTML5 canvas, save jpeg blob and restore to canvas from blob
提问by Anton Gildebrand
I have a canvas #mycanvas
which contains an image. I want to create a blob out of that image, preferably as a jpeg. Here is how i create the blob
我有一个#mycanvas
包含图像的画布。我想从该图像中创建一个 blob,最好是 jpeg。这是我创建 blob 的方法
document.getElementById('mycanvas').toDataURL("image/jpeg").replace(/^data:image\/(png|jpeg);base64,/, "")
How do i recreate the image from this blob, and show it in #mycanvas
again?
我如何从这个 blob 重新创建图像,并#mycanvas
再次显示它?
采纳答案by Anton Gildebrand
Here's how i solved my problem
这是我解决问题的方法
function blob2canvas(canvas,blob){
var img = new Img;
var ctx = canvas.getContext('2d');
img.onload = function () {
ctx.drawImage(img,0,0);
}
img.src = blob;
}
The blob was received when calling canvas.toDataURL("image/jpeg")
调用时收到 blob canvas.toDataURL("image/jpeg")
回答by Leonardo Max Almeida
Anton's answer no longer works as it is. You need this syntax now.
安东的回答不再有效。你现在需要这个语法。
function blob2canvas(canvas,blob){
var img = new window.Image();
img.addEventListener("load", function () {
canvas.getContext("2d").drawImage(img, 0, 0);
});
img.setAttribute("src", blob);
}