> 위챗 애플릿 > 미니 프로그램 개발 > 예제를 통해 미니프로그램에서 캔버스 드래그 기능을 구현하는 방법을 알아보세요.

예제를 통해 미니프로그램에서 캔버스 드래그 기능을 구현하는 방법을 알아보세요.

青灯夜游
풀어 주다: 2021-11-29 19:36:07
앞으로
4072명이 탐색했습니다.

이 기사에서는 코드 예제를 통해 WeChat 애플릿의 캔버스 드래그 요소 기능을 구현하는 방법을 설명하겠습니다.

예제를 통해 미니프로그램에서 캔버스 드래그 기능을 구현하는 방법을 알아보세요.

캔버스 만들기

<canvas type="2d" id="myCanvas" style="height: 600px; width: 500px;"></canvas>
로그인 후 복사

데이터 데이터

// 鼠标状态
statusConfig : {
      idle: 0,       //正常状态
      Drag_start: 1, //拖拽开始
      Dragging: 2,   //拖拽中
},
// canvas 状态
canvasInfo : {
   // 圆的状态
   status: 0,
   // 鼠标在在圆圈里位置放里头
   dragTarget: null,
   // 点击圆时的的位置
   lastEvtPos: {x: null, y: null},
},
로그인 후 복사

캔버스에 원 두 개 그리기

onLoad: function (options) {
    // 设置画布,获得画布的上下文 ctx
    this.getCanvas();
},
getCanvas(){
    // 根据id获取canvas元素,微信小程序无法使用document, 我们需要使用wx.createSelectorQuery()来代替
    const query = wx.createSelectorQuery()
    query.select(&#39;#myCanvas&#39;)
      .fields({ node: true, size: true })
      .exec((res) => {
        const canvas = res[0].node
        // 设置画布的比例
        canvas.width="500";
        canvas.height="600";
        const ctx = canvas.getContext(&#39;2d&#39;)
        // 在画布上画两个圆,将ctx传递过去绘画
        this.drawCircle(ctx, 100, 100, 20);
        this.drawCircle(ctx, 200, 200, 10);
        // 将我们绘画的信息保存起来,之后移动后需要清空画板重新画
        var circles = []
        circles.push({x: 100, y: 100, r: 20});
        circles.push({x: 200, y: 200, r: 10});
        // 不要忘记保存哦
        this.setData({
         circles
        })
      })
   },
// 画圆
drawCircle(ctx, cx, cy, r){
    ctx.save()
    ctx.beginPath()
    ctx.strokeStyle = &#39;yellow&#39;
    ctx.lineWidth = 3
    ctx.arc(cx, cy, r, 0, 2 * Math.PI)
    ctx.stroke()
    ctx.closePath()
    ctx.restore()
},
로그인 후 복사

예제를 통해 미니프로그램에서 캔버스 드래그 기능을 구현하는 방법을 알아보세요.

캔버스에 터치 이벤트 3개 설정

<canvas type="2d" id="myCanvas" 
 bindtouchstart="handleCanvasStart"  bindtouchmove="handleCanvasMove"  bindtouchend="handleCanvasEnd"
 style="height: 600px; width: 500px;">
</canvas>
로그인 후 복사
type트리거 조건
touchstart손가락 터치 동작이 시작됩니다
touchmove터치 후 손가락이 움직입니다
touchcancel전화 수신 알림, 팝업창 등 손가락 터치 동작이 중단됩니다
touchend 손가락 터치 동작이 종료됩니다
tap손가락이 닿았다가 바로 떠나요

터치 동작이 시작되고, 클릭 포인트가 원 안에 있으면 캔버스 정보가 변경됩니다

handleCanvasStart(e){
    // 获取点击点的位置
    const canvasPosition = this.getCanvasPosition(e);
    // 判断点击点的位置在不在圈里,如果不在返回false, 在返回圆的信息
    const circleRef = this.ifInCircle(canvasPosition);
    const {canvasInfo, statusConfig} = this.data;
    // 在圆里的话,改变圆此时的状态信息
    if(circleRef){
      canvasInfo.dragTarget = circleRef;
      //改变拖动状态 idle -> Drag_start
      canvasInfo.status = statusConfig.Drag_start;
      canvasInfo.lastEvtPos = canvasPosition;
    }
    this.setData({
      canvasInfo
    })
  },
// 获取点击点的位置
getCanvasPosition(e){
    return{
      x: e.changedTouches[0].x,
      y: e.changedTouches[0].y
    }
},

// 看点击点击点是不是在圈里
ifInCircle(pos){
    const {circles} = this.data;
    for( let i = 0 ; i < circles.length; i++ ){
      // 判断点击点到圆心是不是小于半径
      if( this.getDistance(circles[i], pos) < circles[i].r ){
        return circles[i]
      }
    }
    return false
  },
// 获取两点之间的距离(数学公式)
getDistance(p1, p2){
    return Math.sqrt((p1.x-p2.x) ** 2 + (p1.y-p2.y) ** 2)
}
로그인 후 복사

The 손가락이 닿고 움직이면 원이 다시 그려집니다

handleCanvasMove(e){
    const canvasPosition = this.getCanvasPosition(e);
    const {canvasInfo, statusConfig, circles} = this.data;
    // 是拖拽开始状态,滑动的大小大于5(防抖)
    if( canvasInfo.status === statusConfig.Drag_start && 
      this.getDistance(canvasPosition, canvasInfo.lastEvtPos) > 5){
        // 改变拖动状态 Drag_start ->  Dragging
        canvasInfo.status = statusConfig.Dragging;
    }else if( canvasInfo.status === statusConfig.Dragging ){
        canvasInfo.dragTarget.x = canvasPosition.x;
        canvasInfo.dragTarget.y = canvasPosition.y;
        // 重新绘制
        const query = wx.createSelectorQuery()
        query.select(&#39;#myCanvas&#39;)
          .fields({ node: true, size: true })
          .exec((res) => {
            const canvas = res[0].node
            canvas.width="500";
            canvas.height="600";
            const ctx = canvas.getContext(&#39;2d&#39;)
            // 遍历circles,把圆重新画一遍
            circles.forEach(c => this.drawCircle(ctx, c.x, c.y, c.r))
          })
    }

    this.setData({
      canvasInfo,
    })
  }
로그인 후 복사

손가락 터치 동작이 끝난 후 canvasInfo 상태를 다시 유휴 상태로 변경합니다

 handleCanvasEnd(e){
    const {canvasInfo, statusConfig} = this.data;
    if( canvasInfo.status === statusConfig.Dragging ){
    // 改变拖动状态 Dragging ->  idle
      canvasInfo.status = statusConfig.idle;
      this.setData({
        canvasInfo
      })
    }
  }
로그인 후 복사

예제를 통해 미니프로그램에서 캔버스 드래그 기능을 구현하는 방법을 알아보세요.

Bilibili의 상사에게 배우지만 WeChat 애플릿과 html 캔버스의 차이 나도 우울해졌어

【관련 학습 추천: 미니 프로그램 개발 튜토리얼

위 내용은 예제를 통해 미니프로그램에서 캔버스 드래그 기능을 구현하는 방법을 알아보세요.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿