canvas常用操作方法
base64转换Blob数据
function dataURLtoBlob(dataurl: string) {
var arr = dataurl.split(','),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
eturn new Blob([u8arr], { type: mime });
}
// 使用示例:
var imgData = canvas.toDataURL({ format: 'png', quality: 1, width: 20000, height: 4000 });
var blob = dataURLtoBlob(imgData);
canvas转换Blob数据
canvas.toBlob(function (blob) {
console.log(blob)
saveAs(blob, '图片下载.jpeg')
})
图片转换base64
function getBase64Image(img) {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, img.width, img.height);
var dataURL = canvas.toDataURL("image/png");
return dataURL
// return dataURL.replace("data:image/png;base64,", "");
}
设置canvas背景图片底色为白色
var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height)
for (var i = 0; i < imageData.data.length; i += 4) {
// 当该像素是透明的,则设置成白色
if (imageData.data[i + 3] == 0) {
imageData.data[i] = 255
imageData.data[i + 1] = 255
imageData.data[i + 2] = 255
imageData.data[i + 3] = 255
}
}
ctx.putImageData(imageData, 0, 0)
涉及的资料
FileSaver.js Github 主页:
FilerServer.js NPM 仓库主页:
canvas-toBlob Github 主页:
canvas-toBlob NPM 仓库主页: