let canvas = document.getElementById("shareImg");
canvas.width = 600;
canvas.height = 600;
let ctx = canvas.getContext("2d");
ctx.globalAlpha = 1;
//创建img标签
var img = new Image();
img.src = imgUrl;
//跨域选项
img.setAttribute("crossOrigin", 'Anonymous');
//文件加载完毕
img.onload = function () {
//图片记载完毕
};
ctx.drawImage(img, 0, 0, 300, 300);//绘制
let url = canvas.toDataURL('image/png', 1)//导出的是base64的图片
以上是全部流程;
但是大部分情况,我们是绘制多张网络图片的,需要对这个方法进行封装;
如果有同学发现,绘制多张图片,在p c端正常,但是移动端失败,可能有一个原因是,需要提前给全部的图片下载下来,下载完毕之后统一drawImage;
function loadAllImages(imgUrls) {
var _load = function (imgUrl) {
//创建img标签
var img = new Image();
img.src = imgUrl;
//跨域选项
img.setAttribute("crossOrigin", 'Anonymous');
return new Promise((resolve, reject) => {
//文件加载完毕
img.onload = function () {
resolve(img);
};
});
}
var _loadAll = function (imgUrls) {
var loadedImageUrls = [];
for (var i = 0, len = imgUrls.length; i < len; i++) {
loadedImageUrls.push(_load(imgUrls[i]));
}
return loadedImageUrls;
}
return Promise.all(_loadAll(imgUrls))
}
let canvasImageArr=[imgurl1,imgurl2,imgurl3,...];//这里替换自己的图片链接
loadAllImages([...canvasImageArr]).then(res => {
let canvas = document.getElementById("shareImg");
canvas.width = 600;
canvas.height = 600;
let ctx = canvas.getContext("2d");
ctx.globalAlpha = 1;
ctx.drawImage(res[0], 0, 0, 300, 300);
ctx.drawImage(res[1], 0, 0, 504, 520);
let url = canvas.toDataURL('image/png', 1)
return url
})
//将上面代码的ctx.drawImage()替换成如下代码:
ctx.save();
ctx.beginPath();
ctx.arc(350, 290, 150, 0, 2 * Math.PI);//ctx.arc(x,y,半径,扇形的大小)
ctx.fill();
ctx.clip();
ctx.drawImage(imgurl, 200, 145, 300, 300);
ctx.restore();