How to render an image blob to a canvas element?
So far i have these two (simplified) functions to capture an image, transform it to a blob and eventually render the blob on a canvas in this codepen, it just returns the default black image.
var canvas = document.getElementById('canvas');
var input = document.getElementById('input');
var ctx = canvas.getContext('2d');
var photo;
function picToBlob() {
var file = input.files[0];
canvas.toBlob(function(blob) {
var newImg = document.createElement("img"),
url = URL.createObjectURL(blob);
newImg.onload = function() {
ctx.drawImage(this, 0, 0);
photo = blob;
URL.revokeObjectURL(url);
};
newImg.src = url;
}, file.type, 0.5);
canvas.renderImage(photo);
}
HTMLCanvasElement.prototype.renderImage = function(blob) {
var canvas = this;
var ctx = canvas.getContext('2d');
var img = new Image();
img.onload = function() {
ctx.drawImage(img, 0, 0)
}
img.src = URL.createObjectURL(blob);
}
input.addEventListener('change', picToBlob, false);
canvas.toBlob
before you draw on it (in yourcanvas.renderImage
, which is async btw) and you wonder why it outputs a transparent image? I'd say it's because you didn't drawn anything on your canvas at the time you tried to export it. Ps: in yourrenderImage
, don't forget to also revoke the URL object, and you'll probably need to resize your canvas. – Hortatory