Front-end canvas generates posters and saves them locally, highly restored

Recently, I found that many small partners have encountered some needs that they need to generate a poster on the front end, and some choose to use plug-ins such as html5canvas,

 But this has a disadvantage that sometimes the generated posters are very blurry and not very easy to use.

Next, share a poster I generated with canvas, you can refer to:

1. 页面上定义一个canvas,设置宽度和高度是设计图的两倍  
<canvas id="positionShareCanvas" ref="positionShareRef" width="1760" height="2100" style="display:none"></canvas>

2. 获取canvas
const canvas = document.getElementById("positionShareCanvas");
const ctx = canvas.getContext("2d");
var img = document.createElement("img");
img.width = 880;        // 设置背景图片宽高,为设计图原始宽高就行
img.height = 1220;
img.src = "xxxxxxx";    // 设置背景图片的地址
img.onload = function () {       // 图片加载完成后
    ctx.drawImage(img, 0, 0);    // 从canvas画布的左上角开始绘制
    ctx.font = "48px Arial";     // 设置字体大小
    ctx.fillStyle = "#979797";   // 设置字体颜色
    ctx.fillText("绘制的文字", 96, 100)    //设置字体,位置在 x坐标,y坐标,这里的x ,y 坐标都是设计图尺寸的两倍,  下面就是一次类推,

    ……………………………………
    ………………

3. 接下来就是保存图片
    var eleLink = document.createElement("a");     
    eleLink.href = canvas.toDataURL(); // 转换后的图片地址
    eleLink.download = `${t('usdtcontract.position')}`;
    document.body.appendChild(eleLink);
    // 触发点击
    eleLink.click();
    // 然后移除
    document.body.removeChild(eleLink);
}

The final effect

 

Personal test is easy to use......

Guess you like

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