我有一个可在画布中移动的圆,该圆不是设定的位置。单击鼠标可以在任何地方创建它。我正在尝试在设定的位置创建两个圆圈(粉红色和黄色),并且我想创建可拖动的圆圈(鼠标单击->能够移动X,Y位置)到画布上的任何位置。我该如何尝试?
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>