<canvas id = "canvas"></canvas>
如何将图片转为canvas === canvas如何绘制图片
const ctx = document.getElementById('canvas').getContext('2d');
const img = new Image();
img.onload = function(){
ctx.drawImage(img, 0, 0);
}
img.src = 'images/xxx.png';
如何将canvas导出为图片
- 方法一
- canvas可以直接导出包含data URL的DOMString
- dataURL格式的图片可以直接赋值到new Image().src上
- DATA URLs,前缀为data:协议的URL,其允许内容创建者向文档中嵌入小文件
-
const canvas = document.getElementById('canvas');
const url = canvas.toDataURL() // 导出包含data URL的DOMString
const img = new Image()
img.src = url
img.onload = function(){
document.body.appendChild(img)
}
方法二
- canvas可以导出为blob二进制文件
- 需要将二进制文件转为DOMString后赋值到new Image().src上
- window.createObjectURL可以将file对象、blob对象、mediaSource对象转为DOMString
- DOMString是一个UTF-16字符串
-
const canvas = document.getElementById('canvas');
canvas.toBlob((blob) => {
const url = window.URL.createObjectURL(blob)
const img = new Image()
img.src = url
img.onload = function(){
document.querySelector('#image').appendChild(img)
}
})
A low performance polyfill based on toDataURL.
- 例如 ios_10_3_3 toBlob 为 undefined
-
if (!HTMLCanvasElement.prototype.toBlob) {
Object.defineProperty(HTMLCanvasElement.prototype, 'toBlob', {
value: function(callback, type="image/png", quality=0.92) {
const dataURL = this.toDataURL(type, quality);
const binStr = atob(dataURL.split(',')[1]);
const len = binStr.length;
const data = new Uint8Array(len);
let i = 0;
while(i < len) {
data[i] = binStr.charCodeAt(i)
i++
}
callback(new Blob([data], {
type: type || 'image/png'
}));
}
})
}