Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

小程序canvas生成的背景图片和UI上的不一样怎么回事?

UI上面生成的背景图片的宽高是550*900 生成的宽高也没错 可是生成的图片明显跟UI上的比例不对 这是怎么回事?

<view hidden="{{hidden}}" class='preview_wrapper'>
    <image class="canvas3" src='{{prurl}}'></image>
</view>
.preview_wrapper {
  z-index: 999999999999;
  position: fixed;
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
  background: rgba(0, 0, 0, 0.4);
}
.canvas3{
  width: 550rpx;
  height: 900rpx;
}
const canvasCtx = wx.createCanvasContext('shareCanvas');
let width = 550; //UI上的宽度
let height = 900; //UI上的高度
let bg = that.data.canvasbg; //背景图片
canvasCtx.drawImage(bg, 0, 0, width, height);
canvasCtx.draw();
setTimeout(function() {
    wx.canvasToTempFilePath({
        x: 0,
        y: 0,
        width: 550,
        height: 900,
        destWidth: 550,
        destHeight: 900,
        canvasId: 'shareCanvas',
        success:res=>{
          that.setData({
            prurl: res.tempFilePath,
            hidden: false
          });
          wx.hideLoading();
        },
        fail: function(res) {
          console.log(res);
          wx.hideLoading();
        }
    });
}, 2000);

canvas生成的
image
UI
image


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

首先, canvas 画布的尺寸必须大于等于目标图片缩放后的尺寸,否则超出区域的部分会被裁剪。
然后考虑下 canvas 被拉伸的可能性,如果 canvas 元素的 CSS 宽高比不等于其画布宽高比,就会出现图片被拉伸的情况。

看起来两种情况都占了,应该可以通过调用绘图上下文的 transform 接口来解决。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...