javascript - 如何使画布中的圆形对象可移动
问题描述
我正在尝试让圆形对象移动,就像鼠标点击时移动一样,当鼠标离开时它会停止。单击时圆圈正在移动,但问题是创建了很多圆圈。我只想在画布上画一个圆圈。
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.beginPath();
canvas.addEventListener('mousedown', function(e) {
this.down = true;
this.X = e.pageX;
this.Y = e.pageY;
}, 0);
canvas.addEventListener('mouseup', function() {
this.down = false;
}, 0);
canvas.addEventListener('mousemove', function(e) {
if (this.down) {
with(ctx) {
ctx.beginPath();
ctx.arc(this.X, this.Y, 50, 0, 2 * Math.PI, true);
ctx.fillStyle = "#FF6A6A";
ctx.fill();
ctx.stroke();
}
this.X = e.pageX;
this.Y = e.pageY;
}
}, 0);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Canvas</title>
</head>
<body>
<canvas id="canvas" style='background-color:#EEE;' width='500px' height='200px'></canvas>
</body>
</html>
解决方案
每次mousemove
使用 绘制事件时都需要清除画布ctx.clearRect(x, y, width, height)
,然后像这样重新绘制圆圈:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.beginPath();
canvas.addEventListener('mousedown', function(e) {
this.down = true;
this.X = e.pageX;
this.Y = e.pageY;
}, 0);
canvas.addEventListener('mouseup', function() {
this.down = false;
}, 0);
canvas.addEventListener('mousemove', function(e) {
if (this.down) {
// clear canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(this.X, this.Y, 50, 0, 2 * Math.PI, true);
ctx.fillStyle = "#FF6A6A";
ctx.fill();
ctx.stroke();
this.X = e.pageX;
this.Y = e.pageY;
}
}, 0);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Canvas</title>
</head>
<body>
<canvas id="canvas" style='background-color:#EEE;' width='500px' height='200px'></canvas>
</body>
</html>
推荐阅读
- macos - 有没有从 Mac OSX 10.15.7 升级到 big sur os 的选项?
- encryption - Serpent 256 位密钥的 Mcrypt 设置
- excel - vba ontime 事件如果超过了设置的时间会发生什么
- java - 在java中匹配两个JsonNode的最佳方法
- facial-landmark-alignment - 如何将 106 转换为 68 个地标点
- html - 具有相对于可见页面的图像高度和最大相对宽度的 CSS flex 布局
- visual-studio-code - SSH 目标,如何“在新选项卡中连接到主机”
- python - 为什么来自“静态”的 URL 不能在烧瓶中进行预览?
- python - SCAPY PAGINATION:无限滚动分页
- python - 亚马逊在用 Python 抓取时总是要求提供验证码