我有一个#mycanvas
包含图像的画布。我想从该图像中创建一个 blob,最好是 jpeg。这是我创建blob的方式
document.getElementById('mycanvas').toDataURL("image/jpeg").replace(/^data:image\/(png|jpeg);base64,/, "")
我如何从这个 blob 重新创建图像,并#mycanvas
再次显示它?
我有一个#mycanvas
包含图像的画布。我想从该图像中创建一个 blob,最好是 jpeg。这是我创建blob的方式
document.getElementById('mycanvas').toDataURL("image/jpeg").replace(/^data:image\/(png|jpeg);base64,/, "")
我如何从这个 blob 重新创建图像,并#mycanvas
再次显示它?
这是我解决问题的方法
function blob2canvas(canvas,blob){
var img = new Img;
var ctx = canvas.getContext('2d');
img.onload = function () {
ctx.drawImage(img,0,0);
}
img.src = blob;
}
调用时收到 blobcanvas.toDataURL("image/jpeg")
安东的答案不再有效。你现在需要这个语法。
function blob2canvas(canvas,blob){
var img = new window.Image();
img.addEventListener("load", function () {
canvas.getContext("2d").drawImage(img, 0, 0);
});
img.setAttribute("src", blob);
}
从 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);
}