[英]HTML5 canvas, save jpeg blob and restore to canvas from blob
I have a canvas #mycanvas
which contains an image.我有一个包含图像的画布
#mycanvas
。 I want to create a blob out of that image, preferably as a jpeg.我想从该图像中创建一个 blob,最好是 jpeg。 Here is how i create the blob
这是我创建 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
显示它?
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")
调用
canvas.toDataURL("image/jpeg")
时接收到 blob
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);
}
Restore to Canvas from Blob sample taken from: https://googlechrome.github.io/samples/image-capture/grab-frame-take-photo.html从 Blob 示例恢复到画布: https : //googlechrome.github.io/samples/image-capture/grab-frame-take-photo.html
// ms is a MediaStreamPointer
let imageCapture = new ImageCapture(ms.getVideoTracks()[0]);
imageCapture.takePhoto()
.then(blob => createImageBitmap(blob))
.then(imageBitmap => {
const canvas = document.getElementById('canvas')
drawCanvas(canvas, imageBitmap);
})
function drawCanvas(canvas, img) {
canvas.width = getComputedStyle(canvas).width.split('px')[0];
canvas.height = getComputedStyle(canvas).height.split('px')[0];
let ratio = Math.min(canvas.width / img.width, canvas.height / img.height);
let x = (canvas.width - img.width * ratio) / 2;
let y = (canvas.height - img.height * ratio) / 2;
canvas.getContext('2d').clearRect(0, 0, canvas.width, canvas.height);
canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height,
x, y, img.width * ratio, img.height * ratio);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.