如何在canvas元素上渲染blob?

问题描述 投票:3回答:1

如何将图像blob渲染到canvas元素?

到目前为止,我有这两个(简化的)函数来捕获图像,将其转换为blob并最终在画布上渲染blob 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);
html5 canvas blob
1个回答
7
投票

我想你需要整理一下你的代码。很难知道你想要实现什么,因为有许多不必要的代码行。主要问题是blob在这里未定义

HTMLCanvasElement.prototype.renderImage = function(blob){

因为photo永远不会在toBlob函数中被初始化...这对于你想要实现的东西是不必要的。

这是您的代码段的简化工作版本

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>
© www.soinside.com 2019 - 2024. All rights reserved.