前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >前端H5生成海报

前端H5生成海报

作者头像
北溟有鱼QAQ
发布2022-09-16 11:18:07
4770
发布2022-09-16 11:18:07
举报
文章被收录于专栏:北溟有鱼QAQ北溟有鱼QAQ

最近项目需要涉及到前端海报合成分享功能,前端靠不上只能自己上... 现学现卖 相关链接

  • https://blog.csdn.net/allway2/article/details/120650927
  • https://jskoa.com/?p=8102
  • https://blog.csdn.net/cuk0051/article/details/108340016
  • https://blog.csdn.net/weixin_41192489/article/details/109351747
  • https://www.zhangxinxu.com/wordpress/2018/02/canvas-text-break-line-letter-spacing-vertical/

CSS代码如下

代码语言:javascript
复制
 * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
}

HTML代码如下

代码语言:javascript
复制
<button id="btn" style="height:50px;width:100%;margin:0 auto">点我生成海报</button>
<!--合成后的海报图-->
<img id="out" src="" style="width:100%;border:1px solid black;margin-top:20px;display: none;">

JS代码如下

代码语言:javascript
复制
 CanvasRenderingContext2D.prototype.wrapText = function (text, x, y, maxWidth, lineHeight) {
        if (typeof text != 'string' || typeof x != 'number' || typeof y != 'number') {
            return;
        }
        var context = this;
        var canvas = context.canvas;
        if (typeof maxWidth == 'undefined') {
            maxWidth = (canvas && canvas.width) || 300;
        }
        if (typeof lineHeight == 'undefined') {
            lineHeight = (canvas && parseInt(window.getComputedStyle(canvas).lineHeight)) || parseInt(window.getComputedStyle(document.body).lineHeight);
        }
        // 字符分隔为数组
        var arrText = text.split('');
        var line = '';
        for (var n = 0; n < arrText.length; n++) {
            var testLine = line + arrText[n];
            var metrics = context.measureText(testLine);
            var testWidth = metrics.width;
            if (testWidth > maxWidth && n > 0) {
                context.fillText(line, x, y);
                line = arrText[n];
                y += lineHeight;
            } else {
                line = testLine;
            }
        }
        context.fillText(line, x, y);
    };


    function nickname(x, y) {
        context.fillStyle = 'grey';
        context.font = '32px  SC';
        context.wrapText("iuu 邀请你一起学习", x, y, 700, 60)
    }

    // 课程标题
    function goodsTitle(x, y) {
        context.fillStyle = 'black';
        context.font = '40px  bold';
        context.wrapText("第131讲:如何提升社会科学类核心期刊投稿的命中率", x, y, 700, 60)
    }

    // 描述
    function shopMsg(x, y) {
        context.fillStyle = 'grey';
        context.font = '25px  bold';
        context.wrapText("— 科研写作研究所", x, y, 700, 60)
    }

    // 图片描述
    function imgMsg(x, y) {
        context.fillStyle = 'grey';
        context.font = '24px  SC';
        context.fillText("长按保存图片", 310, 1250)
    }


    // 背景
    function bgImgScaleToFill(img) {
        var scale = Math.max(canvas.width / img.width, canvas.height / img.height);
        var x = (canvas.width / 2) - (img.width / 2) * scale;
        var y = (canvas.height / 2) - (img.height / 2) * scale;
        context.drawImage(img, x, y, img.width * scale, img.height * scale);
    }

    // 商品图
    function goodsImgScaleToFit(img, x, y) {
        var scale = Math.min(canvas.width / img.width, canvas.height / img.height);
        context.drawImage(img, x, y, img.width * scale, img.height * scale);
    }

    // 二维码
    function qrImgScaleToFill(img, x, y) {
        context.drawImage(img, x, y, img.width, img.height);
    }

    // 头像
    function avatarImgScaleToFill(img, x, y, w, h) {
        context.drawImage(img, x, y, w, h);
    }


    var canvas = document.createElement("canvas");
    var context = canvas.getContext("2d");
    window.onload = function () {
        var btn = document.getElementById("btn");

        var QrImgUrl = "http://fenxiao-guogao.wukongkeyan.com/tm_ca6379f807f89f5e96ebbce4c81203f7_20220719155912.png"
        var AvatarImgUrl = "http://wechatavator-1252524126.file.myqcloud.com/appzissbssa6278/image/compress/u_api_61edfdfd1c284_PWGOuVUIpM.png"
        var GoodsImgUrl = "http://wechatapppro-1252524126.file.myqcloud.com/appzissbssa6278/image/b_u_6170d73860ce7_73CZtcAY/l4z0x8yo02hu.jpg"

        btn.onclick = function () {
            var all = {avatarImg: null, goodsImg: null, qrImg: null}

            var QrImg = new Promise(function (resolve, reject) {
                var qrImg = new Image();
                qrImg.crossOrigin = 'anonymous';
                qrImg.src = QrImgUrl
                qrImg.onload = function () {
                    resolve(qrImg);
                }
            })

            var AvatarImgCircle = new Promise(function (resolve, reject) {
                var cs = document.createElement('canvas');
                var ctx = cs.getContext('2d');
                var avatar = new Image();
                avatar.crossOrigin = 'anonymous';
                avatar.src = AvatarImgUrl
                avatar.onload = function () {
                    cs.width = avatar.width;
                    cs.height = avatar.height;
                    var width = avatar.width;
                    var height = avatar.height;
                    var circle = {x: width / 2, y: height / 2, r: width / 2}
                    ctx.clearRect(0, 0, width, height);
                    ctx.save();
                    ctx.beginPath();
                    ctx.arc(circle.x, circle.y, circle.r, 0, Math.PI * 2, false);
                    ctx.clip();
                    ctx.drawImage(avatar, 0, 0);
                    ctx.restore();
                    // var base64 =
                    var avatarImg = new Image()
                    avatarImg.src = cs.toDataURL("image/png");
                    resolve(avatarImg);
                }
            })
            var GoodsImg = new Promise(function (resolve, reject) {
                var goodsImg = new Image();
                goodsImg.crossOrigin = 'anonymous';
                goodsImg.src = GoodsImgUrl
                goodsImg.onload = function () {
                    resolve(goodsImg);
                }
            })
            Promise.all([QrImg, GoodsImg, AvatarImgCircle]).then(res => {
                all.avatarImg = res[2]
                all.goodsImg = res[1]
                all.qrImg = res[0]
                var bgImg = new Image();
                bgImg.crossOrigin = 'anonymous';
                bgImg.src = 'http://commonresource-1252524126.cdn.xiaoeknow.com/image/l5c2twsm0lm1.png';
                bgImg.onload = function () {
                    canvas.width = 750;
                    canvas.height = 1334;
                    bgImgScaleToFill(bgImg)
                    goodsImgScaleToFit(all.goodsImg, 0, 0)
                    qrImgScaleToFill(all.qrImg, 300, 1060)
                    avatarImgScaleToFill(all.avatarImg, 25, 680, 80, 80)
                    nickname(145, 740)
                    goodsTitle(40, 900)
                    shopMsg(40, 1020)
                    imgMsg(310, 1250)
                    var base64 = canvas.toDataURL();
                    document.getElementById('out').src = base64;
                    document.getElementById('out').style.display = "block";
                }
            })
        }
    }

这个代码主要是进行海报合成,其中注意点事 所有得图片都必须加载完成之后进行合成操作 所以用到了Promise来进行处理

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2022-07-22 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档