canvas生成海报

// vue h5页面,海报生成

<
img :src="drawImg" style="300px;height:527px;" /> drawImg() { // 创建高分辨率画布,可自定义放大倍率 let canvas = this.createHiDPICanvas(256, 450); let ctx = canvas.getContext("2d"); this.renderImage(ctx); setTimeout(() => { this.convertCanvasToImage(canvas); this.popshow = true; }, 500); }, renderImage(ctx) { // 使用Promise加载图片,等图片全部加载完成之后依次绘制 Promise.all([ this.loadImage(this.imgUrl1), this.loadImage(this.imgUrl2), this.loadImage(this.imgUrl3), ]).then((imgs) => { // canvas导出图片png会默认透明背景,jepg默认黑色背景 // 这里将背景设置成白色 ctx.fillStyle = "#fff"; ctx.fillRect(0, 0, 256, 450); ctx.translate(0, 0); // 重新定义起点 ctx.drawImage(imgs[0], 0, 0, 256, 388); this.drawAvatar(ctx, imgs[1], 6, 398, 48); ctx.drawImage(imgs[2], 202, 398, 48, 48); ctx.fillStyle = "rgba(51, 53, 55, 1)"; ctx.font = "13px PingFangSC-Regular,PingFang SC"; ctx.fillText("苦学大叔", 60, 408); ctx.fillStyle = "rgba(138, 142, 145, 1)"; ctx.font = "11px PingFangSC-Regular,PingFang SC"; ctx.fillText(`******公司 | 苦逼程序员`, 60, 424); ctx.fillStyle = "rgba(138, 142, 145, 1)"; ctx.font = "11px PingFangSC-Regular,PingFang SC"; ctx.fillText("177****6620", 60, 442); }); }, loadImage(url) { return new Promise((resolve) => { const img = new Image(); // 解决图片跨域问题 img.setAttribute("crossOrigin", "Anonymous"); img.onload = () => resolve(img); img.src = url; }); }, // 名片头像,圆形 drawAvatar(ctx, src, x, y, w) { const r = w / 2; ctx.save(); ctx.arc(x + r, y + r, r, 0, 2 * Math.PI, false); ctx.clip(); ctx.drawImage(src, x, y, w, w); ctx.restore(); }, convertCanvasToImage(canvas) { let image = new Image(); image.src = canvas.toDataURL("image/png"); this.drawImg = image.src; }, // 创建高分辨率画布 createHiDPICanvas(w, h, ratio) { const PIXEL_RATIO = (function () { const c = document.createElement("canvas"), ctx = c.getContext("2d"), dpr = window.devicePixelRatio || 1, bsr = ctx["webkitBackingStorePixelRatio"] || ctx["mozBackingStorePixelRatio"] || ctx["msBackingStorePixelRatio"] || ctx["oBackingStorePixelRatio"] || ctx["backingStorePixelRatio"] || 1; return dpr / bsr; })(); if (!ratio) { ratio = PIXEL_RATIO; } const can = document.createElement("canvas"); can.width = w * ratio; can.height = h * ratio; can.style.width = w + "px"; can.style.height = h + "px"; can.getContext("2d").setTransform(ratio, 0, 0, ratio, 0, 0); return can; }

效果图:

原文地址:https://www.cnblogs.com/az4215/p/13542172.html