• 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; }

    效果图:

  • 相关阅读:
    C++ 根据对象名字创建对象
    Google是如何测试的(一)
    lex yacc 学习
    C语言宏定义时#(井号)和##(双井号)的用法
    更多编译器对C++11的支持比较
    用C++11替代Boost的实验之三
    最先进的开源游戏引擎KlayGE 4.2发布
    各编译器对C++11的支持比较
    在Android模拟器上的一些小陷阱
    推出KlayGE Foundation Library
  • 原文地址:https://www.cnblogs.com/az4215/p/13542172.html
Copyright © 2020-2023  润新知