html:
<canvas id="canvas" width="300" height="450" ></canvas>
js:
function downLoadShareImg(){
let canvas = document.getElementById("canvas");
canvas.width = 300;
canvas.height = 450;
let context = canvas.getContext("2d");
// 设置简介
let info = row.zhuyaoxingzhuang;
var n = 15; // 每行显示几个字
for (var i = 0, l = info.length; i < l / n; i++) {
var sliceStr = info.slice(n * i, n * (i + 1));
context.font = "12px Arial";
context.fillStyle = "#8C9198";
var rowHeight = 355 + i * 18;
context.fillText(sliceStr, 15, rowHeight);
if (i >= 4) {
break;
}
}
// 设置小程序码,网络图片可不在onload 后设置;生成码时图片已加载完毕
let qrcodepath = row.reserveimg;
let qrcodeImg = new Image();
qrcodeImg.src = qrcodepath;
context.drawImage(qrcodeImg, 212, 285, 75, 75);
// 绘制本地图片,要在onload 加载图片后绘制
let companyPath = "../../../src/assets/logo.jpg";
let companyImg = new Image();
companyImg.crossOrigin = "anonymous";
companyImg.onload = function () {
context.drawImage(companyImg, 15, 270, 50, 50);
};
companyImg.src = companyPath;
//把画板内容绘制成图片并下载
setTimeout((res) => {
let dataURL = canvas.toDataURL("image/png");
var save_link = document.createElement("a");
save_link.href = dataURL;
save_link.download ="分享图.png";
var clickevent = document.createEvent("MouseEvents");
clickevent.initEvent("click", true, false);
save_link.dispatchEvent(clickevent);
}, 500);
}
!!!
1 web中用webpack编辑使用本地图片要用绝对路径;例如:'/dist/logo.png'