Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render a blob on a canvas element?

Tags:

html

canvas

blob

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);
like image 200
ohav ben yanai Avatar asked Jun 24 '16 02:06

ohav ben yanai


People also ask

How do you get blobs out of canvas?

The HTMLCanvasElement. toBlob() method creates a Blob object representing the image contained in the canvas. This file may be cached on the disk or stored in memory at the discretion of the user agent. The desired file format and image quality may be specified.


Video Answer


1 Answers

I think you need to tidy up your code a bit. It's hard to know what you are trying to achieve because there are many unnecessary lines of code. The main problem is that blob is coming undefined here

HTMLCanvasElement.prototype.renderImage = function(blob){

because photo never gets initialized here inside the toBlob function...which is unnecessary for what you are trying to achieve.

Here's a simplified working version of your code snippet

var canvas = document.getElementById('canvas');
var input = document.getElementById('input');


  function picToBlob() {
    canvas.renderImage(input.files[0]);
  }

HTMLCanvasElement.prototype.renderImage = function(blob){
  
  var ctx = this.getContext('2d');
  var img = new Image();

  img.onload = function(){
    ctx.drawImage(img, 0, 0)
  }

  img.src = URL.createObjectURL(blob);
};

input.addEventListener('change', picToBlob, false);
<input type='file' accept='image' capture='camera' id='input'>
<canvas id = 'canvas'></canvas>
like image 188
Leo Avatar answered Sep 23 '22 11:09

Leo