小程序模板:专业的小程序模板与静态模板分享平台
小程序
教程
搜索
当前位置 : 首页> 小程序教程> 微信小程序canvas画布实现文字自由缩放、移动功能

微信小程序canvas画布实现文字自由缩放、移动功能

一、核心实现架构设计

  1. 画布初始化(新版Canvas 2D)


// JS初始化(适配视网膜屏)
const query = wx.createSelectorQuery().select('#myCanvas')
.fields({ node: true, size: true }).exec(res => {
  const canvas = res[0].node;
  const dpr = wx.getSystemInfoSync().pixelRatio;
  canvas.width = res[0].width * dpr;
  canvas.height = res[0].height * dpr;
  ctx = canvas.getContext('2d');
  ctx.scale(dpr, dpr); // 关键:坐标系缩放适配
});

2.触摸事件驱动

// 事件绑定(WXML需声明)


二、文字动态缩放实现

  1. 手势检测逻辑

let initialDistance = 0;
// 双指触摸计算间距
handleTouchStart(e) {
  if (e.touches.length === 2) {
    const x1 = e.touches[0].clientX, y1 = e.touches[0].clientY;
    const x2 = e.touches[1].clientX, y2 = e.touches[1].clientY;
    initialDistance = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2);
  }
}


2.动态缩放坐标系

handleTouchMove(e) {
  if (e.touches.length === 2) {
    // 计算当前双指间距
    const currentDistance = ... // 同上逻辑
    const scale = currentDistance / initialDistance;
    
    // 以双指中心点为缩放原点
    const centerX = (e.touches[0].clientX + e.touches[1].clientX) / 2;
    const centerY = (e.touches[0].clientY + e.touches[1].clientY) / 2;
    
    ctx.translate(centerX, centerY);
    ctx.scale(scale, scale);
    ctx.translate(-centerX, -centerY);
    this.redrawText(); // 触发重绘
  }
}


三、文字自由移动实现

  1. 单指拖拽检测

let isDragging = false;
let lastPos = { x: 0, y: 0 };

handleTouchStart(e) {
  if (e.touches.length === 1) {
    const touchX = e.touches[0].clientX;
    const touchY = e.touches[0].clientY;
    // 判断触点是否在文字区域内(需维护文字坐标数据)
    if (this.checkInTextArea(touchX, touchY)) {
      isDragging = true;
      lastPos = { x: touchX, y: touchY };
    }
  }
}

2. 坐标偏移计算

handleTouchMove(e) {
  if (isDragging) {
    const deltaX = e.touches[0].clientX - lastPos.x;
    const deltaY = e.touches[0].clientY - lastPos.y;
    this.textData.x += deltaX; // 更新文字坐标
    this.textData.y += deltaY;
    lastPos = { x: e.touches[0].clientX, y: e.touches[0].clientY };
    this.redrawText();
  }
}

联系客服 意见反馈

签到成功!

已连续签到1天,签到3天将获得积分VIP1天

知道了