1. <canvas id = "canvas"></canvas>

如何将图片转为canvas === canvas如何绘制图片

  1. const ctx = document.getElementById('canvas').getContext('2d');
  2. const img = new Image();
  3. img.onload = function(){
  4. ctx.drawImage(img, 0, 0);
  5. }
  6. img.src = 'images/xxx.png';

如何将canvas导出为图片

image.pngimage.png

  • 方法一
  • canvas可以直接导出包含data URL的DOMString
  • dataURL格式的图片可以直接赋值到new Image().src上
  • DATA URLs,前缀为data:协议的URL,其允许内容创建者向文档中嵌入小文件
  • 链接

    1. const canvas = document.getElementById('canvas');
    2. const url = canvas.toDataURL() // 导出包含data URL的DOMString
    3. const img = new Image()
    4. img.src = url
    5. img.onload = function(){
    6. document.body.appendChild(img)
    7. }
  • 方法二

  • canvas可以导出为blob二进制文件
  • 需要将二进制文件转为DOMString后赋值到new Image().src上
  • window.createObjectURL可以将file对象、blob对象、mediaSource对象转为DOMString
  • DOMString是一个UTF-16字符串
  • 链接

    1. const canvas = document.getElementById('canvas');
    2. canvas.toBlob((blob) => {
    3. const url = window.URL.createObjectURL(blob)
    4. const img = new Image()
    5. img.src = url
    6. img.onload = function(){
    7. document.querySelector('#image').appendChild(img)
    8. }
    9. })
  • A low performance polyfill based on toDataURL.

  • 例如 ios_10_3_3 toBlob 为 undefined
  • 链接

    1. if (!HTMLCanvasElement.prototype.toBlob) {
    2. Object.defineProperty(HTMLCanvasElement.prototype, 'toBlob', {
    3. value: function(callback, type="image/png", quality=0.92) {
    4. const dataURL = this.toDataURL(type, quality);
    5. const binStr = atob(dataURL.split(',')[1]);
    6. const len = binStr.length;
    7. const data = new Uint8Array(len);
    8. let i = 0;
    9. while(i < len) {
    10. data[i] = binStr.charCodeAt(i)
    11. i++
    12. }
    13. callback(new Blob([data], {
    14. type: type || 'image/png'
    15. }));
    16. }
    17. })
    18. }