【问题标题】:How to render a blob on a canvas element?如何在画布元素上呈现 blob?
【发布时间】:2016-10-26 13:44:45
【问题描述】:

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

到目前为止,我有这两个(简化的)函数来捕获图像,将其转换为 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);

【问题讨论】:

  • 您在绘制之前调用canvas.toBlob(在您的canvas.renderImage 中,这是异步的顺便说一句),您想知道为什么它会输出透明图像?我会说这是因为您在尝试导出画布时没有在画布上绘制任何内容。 Ps:在你的renderImage,别忘了也撤销URL对象,你可能需要调整你的画布大小。

标签: html canvas blob


【解决方案1】:

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

HTMLCanvasElement.prototype.renderImage = function(blob){

因为photo 永远不会在toBlob 函数内被初始化...这对于您想要实现的目标来说是不必要的。

这是您的代码 sn-p 的简化工作版本

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>

【讨论】:

  • 我也在研究这种方法,希望坚持使用原始数据(来自getImageData),但由于URL.createObjectURL 只是ends up creating a string 反正我最终跳过了一步,直接去了@ 987654330@ 代替我的图像src
  • 我不明白为什么这种不好的做法会被赞成,修改原型是一种不好的做法并会导致问题。
  • @vasilevich 因为问题的上下文与最佳实践无关……如果您不喜欢答案,请随意添加您的答案
【解决方案2】:

你可以像下面这样使用它

function renderImage(canvas, blob) {
  const ctx = canvas.getContext('2d')
  const img = new Image()
  img.onload = (event) => {
    URL.revokeObjectURL(event.target.src) // ? This is important. If you are not using the blob, you should release it if you don't want to reuse it. It's good for memory.
    ctx.drawImage(event.target, 0, 0)
  }
  img.src = URL.createObjectURL(blob)
}

下面是一个例子

/**
 * @param {HTMLCanvasElement} canvas: https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API
 * @param {Blob} blob: https://developer.mozilla.org/en-US/docs/Web/API/Blob
 * */
function renderImage(canvas, blob) {
  const ctx = canvas.getContext('2d')
  switch (blob.type) {
    case "image/jpeg": // Normally, you don't need it (switch), but if you have a special case, then you can consider it.
    case "image/png":
      const img = new Image()
      img.onload = (event) => {
        URL.revokeObjectURL(event.target.src) // Once it loaded the resource, then you can free it at the beginning.
        ctx.drawImage(event.target, 0, 0)
      }
      img.src = URL.createObjectURL(blob)
      break  
  }
}

// ? below is test
(() => {
  const canvas = document.querySelector('canvas')
  const input = document.querySelector('input')
  input.addEventListener('change',
    (event) => {
      const file = event.target.files[0]
      const blob = new Blob(
        [file],
        {"type": file.type} // If the type is unknown, default is empty string.
      )
      renderImage(canvas, blob)
    }
  )
})()
<div><input type='file' accept='.png,.jpg'></div>
<canvas></canvas>

另一个例子告诉你revokeObjectURL有什么作用。

<div></div>
<canvas width="477" height="600"></canvas>
<script>
  async function renderImage(canvas, blob, isNeedRevoke=true) {
    const ctx = canvas.getContext('2d')
    const img = new Image() // The upper part of the painting.
    const img2 = new Image() // The lower part of the painting.

    await new Promise(resolve => {
      img.onload = (event) => {
        if (isNeedRevoke) {
          URL.revokeObjectURL(event.target.src)
        }
        ctx.drawImage(event.target,
          0, 0, 477, 300,
          0, 0, 477, 300
        )
        resolve()
      }
      img.src = URL.createObjectURL(blob)
      setTimeout(resolve, 2000)
    }).then(() => {
      img2.onload = (event) => {
        ctx.drawImage(event.target,
          0, 300, 477, 300,
          0, 300, 477, 300
        )
      }
      img2.src = img.src // ? If URL.revokeObjectURL(img.src) happened, then img2.src can't find the resource, such that img2.onload will not happen.
    })
  }

  function CreateTestButton(canvas, btnText, isNeedRevoke) {
    const button = document.createElement("button")
    button.innerText = btnText
    button.onclick = async (event) => {
      canvas.getContext("2d").clearRect(0, 0, canvas.width, canvas.height)  // clear canvas
      fetch("https://upload.wikimedia.org/wikipedia/commons/thumb/6/6a/PNG_Test.png/477px-PNG_Test.png")
        .then(async response=>{
          const blob = await response.blob()
          renderImage(canvas, blob, isNeedRevoke)
        }).catch(err=>console.error(err))
    }
    return button
  }

  (() => {
    window.onload = () => {
      const canvas = document.querySelector('canvas')
      const div = document.querySelector('div')
      const btn1 = CreateTestButton(canvas, "Without URL.revokeObjectURL", false)
      const btn2 = CreateTestButton(canvas, "URL.revokeObjectURL", true)
      div.append(btn1, btn2)
    }
  })()
</script>

【讨论】:

    【解决方案3】:

    您也可以使用createImageBitmap 直接将 blob 渲染到画布中:

    createImageBitmap(blob).then(imageBitmap=>{ctx.drawImage(imageBitmap,0,0)})
    

    var canvas = document.getElementById('canvas');
    var input = document.getElementById('input');
    
    
    function blobToCanvas() {
      createImageBitmap(input.files[0]).then(imageBitmap => {
        console.log(imageBitmap);
        canvas.getContext('2d').drawImage(imageBitmap, 0, 0)
      })
    }
    
    
    input.addEventListener('change', blobToCanvas, false);
    <input type='file' accept='image' capture='camera' id='input'>
    <canvas id='canvas'></canvas>

    【讨论】:

      猜你喜欢
      • 2017-07-30
      • 1970-01-01
      • 2020-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-14
      相关资源
      最近更新 更多