如何使两个圆形对象(在画布内部)可移动?

时间:2019-07-29 08:23:23

标签: javascript canvas click drag movable

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

1 个答案:

答案 0 :(得分:0)

ViewHolder
ViewHolder

提琴:https://jsfiddle.net/eguneys/qgwtaL2p/18/