如何在画布元素上渲染斑点? [英] How to render a blob on a canvas element?

查看:73
本文介绍了如何在画布元素上渲染斑点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将图像Blob渲染到画布元素?

How to render an image blob to a canvas element?

到目前为止,我具有这两个(简化的)函数来捕获图像,将其转换为斑点并最终在画布上渲染斑点 在此Codepen中,它仅返回默认的黑色图像.

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);

推荐答案

我认为您需要整理一下代码.由于有许多不必要的代码行,因此很难知道您要实现的目标.主要问题是blob在这里未定义

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){

因为photo从未在toBlob函数内部初始化...对于您要实现的目标来说是不必要的.

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>

这篇关于如何在画布元素上渲染斑点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆