javascript - 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;
}
}
解决方案
您必须在 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
}
我还建议将上下文分配为变量,而不是每次都获取它。
推荐阅读
- excel - 如何在 Excel 中创建自动 2 周总计?
- javascript - 如何将焦点集中在一个输入上而不是 React 组件中的所有输入上?
- php - 从输入字段过滤 xss/脚本
- php - 在数据透视表中呈现数百万行
- mysql - 在nodeJS中从MYSQL中的左连接查询中选择
- python - 如何在python中创建具有两个不同变量参数的类实例?
- php - 从子网址重定向到父网址
- excel - 如何使用 Excel VBA 将值输入到网页的下拉框中
- sql - 导出导入oracle
- c# - 有什么方法可以从用户那里获取输入,然后将输入永久保存在程序中,而无需将其写入计算机或写入云数据库