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

How can I make two circle objects (inside the canvas ) movable?

我有一个圆在canvas可以移动,而且圆不是设定的位置。单击鼠标时,它会在任何地方创建。我正在尝试在设定位置创建两个圆圈(粉色和黄色),并且我想创建可拖动的圆圈(鼠标单击 -> 能够移动 X、Y 位置)到 canvas 上的任何位置.我该如何尝试?

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>

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

var model = {
  circle1: { x: 200, y: 200 },
  circle2: { x: 200, y: 200 }
};

var radius = 50;

function view(ctx, model) {
  function circle(c) {
   ctx.beginPath();

   ctx.beginPath();
   ctx.arc(c.x, c.y, radius, 0, 2 * Math.PI, true); 
   ctx.fillStyle = "#FF6A6A";
   ctx.fill();
   ctx.stroke();
 }

 // clear canvas
 ctx.clearRect(0, 0, canvas.width, canvas.height);

 circle(model.circle1);
 circle(model.circle2);
}

function redraw() {
  view(ctx, model);
}

redraw();

function getCircleForPosition(x, y) {
  function intersect(a, b) {
    var d2 = Math.pow(a.x - b.x, 2) + Math.pow(a.y - b.y, 2);
    r2 = Math.pow(radius, 2);
    return d2 < r2;
  }

  return [model.circle1, model.circle2].find(circle => intersect(circle, { x, y }));
}


canvas.addEventListener('mousedown', function(e) {
  model.dragging = getCircleForPosition(e.pageX, e.pageY);
}, 0);
canvas.addEventListener('mouseup', function() {
  model.dragging = undefined;
}, 0);
canvas.addEventListener('mousemove', function(e) {
  if (model.dragging) {
    model.dragging.x = e.pageX;
    model.dragging.y = e.pageY;
    redraw();
  }
}, 0);
 <canvas id="canvas" style='background-color:#EEE;' width='500px' height='500px'></canvas>

fiddle: https://jsfiddle.net/eguneys/qgwtaL2p/18/