首页 > 解决方案 > Vue.js 画布元素跟随鼠标

问题描述

我在 Vue 中基于 HTML 画布制作了颜色选择器,我想在颜色选择器上添加显示活动颜色的透明圆圈,它将跟随画布上的鼠标。

我试图将此代码更改为我的用法:让“球”在画布上跟随鼠标,这就是我得到的:

在此处输入图像描述

如您所见,我的圆圈跟随鼠标位置,但留下痕迹。鼠标位置动态更新为状态,并且我的函数中的 XY 数据是从状态中接收的。

loop(X, Y) {
   this.moveCursor(X, Y)
   requestAnimationFrame(this.loop)
},
moveCursor(X, Y) {
   const colorPickerBlock = document.getElementById('color_picker-block');
   const blockCtx = colorPickerBlock.getContext('2d');

   blockCtx.beginPath();
   blockCtx.arc(X, Y, 6, 0, 2 * Math.PI);
   blockCtx.fillStyle = "transparent";
   blockCtx.fill();
   blockCtx.lineWidth = 1;
   blockCtx.strokeStyle = "white";
   blockCtx.stroke();                
   },
mousedown(event) {
   this.isDragActive = true;
},
mousemove(event) {
  if (this.isDragActive) {
        this.changeLocalColor(event)
        this.loop(this.getActiveElementColor.X, this.getActiveElementColor.Y)
 }
},
mouseup(event) {
   if (this.isDragActive) {
        this.isDragActive = false;
   }
}

标签: javascriptvue.jscanvas

解决方案


您必须在 moveCursor 之前将画布的状态重置为初始状态。我不知道画布是仅用于显示圆形还是用于显示调色板。如果画布仅显示圆圈,那么您需要

context.clearRect(0, 0, canvas.width, canvas.height);

否则你还需要再次绘制整个调色板。

resetPalette ()
{
    this.context.clearRect(0, 0, canvas.width, canvas.height);
    // steps to init palette from the start
}

我还建议将上下文分配为变量,而不是每次都获取它。


推荐阅读