(小程序)canvas 绘制图片做背景(新手向)

小程序绘制图片为背景,首先我们需要把图片先下载下来(这里最好是封装一个函数,因为背景不可能只有一张的)下面是代码,一般直接复制就能使用,有可能需要微调

// 获取图片信息
getImageInfo(image) {
    return new Promise((req, rej) => {
    uni.getImageInfo({
     src: image,
     success: function (res) {
     req(res);
    },
   });
 });
},

// 使用方法
let headerPhtot = await this.getImageInfo(this.userInfo.avatarUrl);
// 这里会返回一个对象 path是图片地址(返回一个本地文件 http://开头)就可以在canvas ctx.drawImage使用
let top = 0;
let left = 0;
let canvasW = 200;
let canvasH = 200;
ctx.drawImage(headerPhtot.path, left, top, canvasW, canvasH);

//裁剪图片使用
let shareBg = this.getAspectFillModelInfo(this.brickUrlData.width, this.brickUrlData.height, 68, 91, 613, 992);
ctx.drawImage(this.brickUrlData.path, shareBg.dx, shareBg.dy, shareBg.dw, shareBg.dh, shareBg.sx, shareBg.sy, shareBg.sw, shareBg.sh); // drawImage(图片路径,x,y,绘制图像的宽度,绘制图像的高度)

// 裁剪图片
getAspectFillModelInfo(oWidth, oHeight, x, y, width, height) {
  // 高比宽大 宽是短边
  let aspect = oHeight / oWidth;
  let sw = width;
  let sh = aspect * sw;
  let dx = 0;
  let dy = (oHeight - height * (oHeight / sh)) / 2;
  let dw = oWidth;
  if (aspect < 1) {
    // 高比宽小 高是短边
    aspect = oWidth / oHeight;
    let scale = aspect * height; // 宽度比例
    sh = height;
    sw = width; //11440
    dw = (width / scale) * oWidth;
    dy = 0;
    dx = (oWidth - width * (oWidth / scale)) / 2;
  }
  return {
    dx, // 可选。开始剪切的 x 坐标位置。
    dy, // 可选。开始剪切的 y 坐标位置。
    dw: dw, // 可选。被剪切图像的宽度。
    dh: oHeight, //可选。被剪切图像的高度。
    sx: x, // 在画布上放置图像的 x 坐标位置。
    sy: y, // 在画布上放置图像的 y 坐标位置。
    sw, // 可选。要使用的图像的宽度。(伸展或缩小图像)
    sh, //可选。要使用的图像的高度。(伸展或缩小图像)
  };
},


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值