小程序 canvas 海报(图片、字体封装方法)解决导出海报模糊问题

最近真是画了一堆canvas海报画到头秃~~~(偷偷说!!产品经理我恨你!!)

来和大家分享一波本媛写的canvas方法封装

1、封装图片

//width:图片长度
//height:图片高度
//x:离左边的距离
//y:离上边的距离
//img:图片路径

imgChange(ctx, canvas, width, height, x, y, img) {
    const headerImg = canvas.createImage();
    headerImg.src = img;
    headerImg.onload = () => {
      ctx.drawImage(headerImg, x, y, width, height);
    }
  }

2、字体长度

//title:字体
//length:控制字体数量(用不到可以删了)
fontwidth(ctx, title,length) {
    var l = 18
    if(length){
      l = length
    }
    if (title.length > l) {
      title = title.substr(0, l) + '...'//超出一定字数隐藏
    }
    const onetitle = ctx.measureText(title)

    return onetitle.width
},

3、字体

//title:字体
//color:颜色
//size:字体样式(格式 同css font)
//fizelength:限制字体长度
font(ctx, title, x, y, color, size,fizelength) {
    ctx.fillStyle = color
    if (size) {
      ctx.font = size
    }
    if(!fizelength){
      fizelength = 18
    }
    if (title.length > fizelength) {
      title = title.substr(0, fizelength) + '...'
    }
    ctx.fillText(title, x, y)
  }

重点!!!

图片导出时候会出现图片和字体模糊

在创建画布的时候记得

const dpr = wx.getSystemInfoSync().pixelRatio//获取当前设备像素

canvas.width = res[0].width * dpr

canvas.height = res[0].height * dpr

(宽高都要乘以dpr哦~~~)

--------------2022-06-09 

补充 :canvas的长宽需要和css中设置的长宽一致哦~~~

         (不一致的话,安卓没问题,ios海报导出会缺少的)

好了就是这样~~创建画布就不写了指步小程序文档

猜你喜欢

转载自blog.csdn.net/sxmzhw/article/details/124195682