小程序使用movable-view组件实现编辑头像的功能之后如何将他渲染到canvas?

image.png

使用小程序movable-view组件实现编辑头像的功能,包括放大缩小、拖拽移动的功能。
但是现在渲染到canvas中犯了难,如果单纯是拖动图片,计算x和y就能渲染到canvas。
加了放大缩放功能之后多了个scale,x和y和scale这3个数据该如何配合着计算,我没有一点头绪,恳求各位大神帮帮忙?
<movable-area scale-area :style="{width: '516rpx', height: `${canvasHeight}rpx`, overflow: 'hidden'}">
    <movable-view
      @change="imgChange"
      @scale="scaleChange"
      :scale-value="scaleValue"
      :x="moveX"
      :y="moveY"
      :style="{width: `${imgWidth}px`, height: `${imgHeight}px`}"
      :scale-min="0.1"
      scale class="max"
      direction="all"
      >
      <image :style="{width: `${imgWidth}px`, height: `${imgHeight}px`, display:block}" :src="user.idPhoto?.sourceUrl" />
    </movable-view>
  </movable-area>

<button @click="renderItem">保存头像<button>

// 渲染到canvas
const renderItem = () => {
  console.log(oldX, oldY, oldScale);
  // shearImage(user.idPhoto?.sourceUrl, realWidth.value, realHeight.value, oldScale, oldX, oldY)
  debugger
}

demo在这:https://developers.weixin.qq.com/s/6Ewr8cmY72LG

阅读 2.8k
2 个回答
const renderItem = () => {
  const canvas = wx.createCanvasContext('yourCanvasId');
  const img = user.idPhoto?.sourceUrl;
  const imgWidth = imgWidth * oldScale; // 考虑缩放后的宽度
  const imgHeight = imgHeight * oldScale; // 考虑缩放后的高度


  const sx = 0;
  const sy = 0;
  const sWidth = imgWidth;
  const sHeight = imgHeight;
  const dx = oldX;
  const dy = oldY;
  const dWidth = imgWidth;
  const dHeight = imgHeight;

  canvas.drawImage(img, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);
  canvas.draw();
};
// 假定输出宽高为 258px*332px
const [width, height] = [258, 332];

canvas.drawImage(
  img,
  -moveX / scale,
  -moveY / scale,
  width / scale,
  height / scale,
  0,
  0,
  width,
  height
);
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题