h5 uses canvas to draw posters and save them locally

I recently worked on a project, and the requirements are as follows: save the poster locally, as shown in the figure

After clicking save, it needs to be downloaded to the local

At the beginning, I used html2canvas to find a plug-in, which can be used, but I found that the saved pictures are very blurry, as follows:

This is definitely not possible, so I decided to write a handwritten one with canvas

It's also very simple, let's talk about the idea,

  1. It is to create a canvas first, and then wait for the picture to be loaded and then draw the picture on the canvas.

  1. Since the QR code is requested asynchronously, create another image of the QR code in the onload method of the previous img,

  1. Then paint on this canvas,

  1. Use canvas's toDataURL() to convert to base64 image address

  1. Finally, use the download function of the a tag to save it locally

Not much to say, the code:

// 使用canvas绘制图片
const generateCanvas = (
    url: string = "/assets/images/img-invite1.png"
): void => {
    var c: any = document.getElementById("canvas");
    var ctx = c.getContext("2d");    //创建画布
    var img = document.createElement("img");
    img.width = 1050;          
    img.height = 1695;
    img.src = url;
    img.onload = function () {     //图片加载完成之后
        ctx.drawImage(img, 0, 0, 1050, 1695);    // 后面两个参数可以尽量大一点,让图片更清晰,需要与图片宽高一致
        ctx.font = "35px Arial";
        ctx.fillStyle = "#fff";
        ctx.fillText(`我的邀请码:${userInfo.value.promotionCode}`, 380, 1550);
        var img1 = document.createElement("img");    //创建第二个图片,这是二维码图片
        img1.width = 300;
        img1.height = 300;
        img1.src = inviteImgCode.value;           //inviteImgCode.value是请求的二维码地址
        img1.onload = function () {             
            ctx.drawImage(img1, 380, 1100, 300, 300);  // 再绘制一遍
            var eleLink = document.createElement("a");     // 下面就是保存的步骤了,很简单 自行看看
            eleLink.href = c.toDataURL(); // 转换后的图片地址
            eleLink.download = "海报";
            document.body.appendChild(eleLink);
            // 触发点击
            eleLink.click();
            // 然后移除
            document.body.removeChild(eleLink);
        };
    };
};

The final effect is as follows, very clear

Friends in need look for food by themselves hahaha~,

Guess you like

Origin blog.csdn.net/weixin_48309048/article/details/129683423