uniapp如何通过移动圆环的小球实现温度调整功能

在uniapp中,我想实现一个通过移动圆环上的小球来调整温度的功能,类似一些智能家居APP中的温度调节控件。请问应该如何实现这样的交互效果?具体需要用到哪些组件或API?能否提供一个简单的实现思路或代码示例?

2 回复

在uniapp中,可通过touchmove事件监听小球拖动,动态改变圆环位置,并映射到温度值(如0-100)。小球位置变化时,更新温度显示,实现温度调整功能。


在 UniApp 中,可以通过自定义组件或 Canvas 实现移动圆环小球调整温度的功能。以下是使用 Canvas 的简单实现步骤:

  1. 创建 Canvas 组件
    在页面中添加 Canvas 元素,并设置宽高:

    <template>
      <view>
        <canvas canvas-id="tempCanvas" :style="{ width: '300px', height: '300px' }"></canvas>
        <text>当前温度:{{ currentTemp }}°C</text>
      </view>
    </template>
    
  2. 绘制圆环和小球
    onReady 生命周期中绘制初始圆环和可拖动小球:

    export default {
      data() {
        return {
          currentTemp: 20, // 初始温度
          ctx: null
        };
      },
      onReady() {
        this.ctx = uni.createCanvasContext('tempCanvas', this);
        this.drawRing();
      },
      methods: {
        drawRing() {
          const { ctx } = this;
          const centerX = 150, centerY = 150, radius = 80;
          
          // 绘制背景圆环
          ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI);
          ctx.setStrokeStyle('#e0e0e0');
          ctx.setLineWidth(10);
          ctx.stroke();
          
          // 绘制温度进度(根据 currentTemp 计算角度)
          const angle = (this.currentTemp / 50) * 2 * Math.PI; // 假设温度范围 0-50°C
          ctx.arc(centerX, centerY, radius, 0, angle);
          ctx.setStrokeStyle('#ff6600');
          ctx.stroke();
          
          // 绘制可拖动小球
          const ballX = centerX + radius * Math.sin(angle);
          const ballY = centerY - radius * Math.cos(angle);
          ctx.arc(ballX, ballY, 15, 0, 2 * Math.PI);
          ctx.setFillStyle('#ff6600');
          ctx.fill();
          
          ctx.draw();
        }
      }
    };
    
  3. 添加触摸事件
    监听 Canvas 的触摸移动事件,根据手指位置计算温度并更新小球位置:

    methods: {
      onTouchMove(e) {
        const touchX = e.touches[0].x;
        const touchY = e.touches[0].y;
        const centerX = 150, centerY = 150, radius = 80;
        
        // 计算触摸点相对于圆心的角度
        const angle = Math.atan2(touchX - centerX, centerY - touchY);
        let normalizedAngle = angle < 0 ? angle + 2 * Math.PI : angle;
        
        // 转换为温度值(0-50°C)
        this.currentTemp = Math.round((normalizedAngle / (2 * Math.PI)) * 50);
        this.drawRing();
      }
    }
    

    在模板中绑定事件:

    <canvas 
      canvas-id="tempCanvas" 
      @touchmove="onTouchMove"
      :style="{ width: '300px', height: '300px' }"
    ></canvas>
    
  4. 优化交互

    • 添加触摸开始事件(@touchstart)提升响应速度
    • 限制小球仅在圆环轨迹上移动
    • 添加温度变化动画

注意事项

  • 需在 uni.createCanvasContext 中指定 this 以兼容小程序环境
  • 实际角度计算需根据温度范围调整
  • 可封装为组件复用

此方案通过 Canvas 实现可视化交互,用户拖动小球即可实时调整温度值。

回到顶部