如何使画布中的圆形对象移动

时间:2019-07-28 09:31:00

标签: javascript canvas html5-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) {
    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>

1 个答案:

答案 0 :(得分:0)

每次使用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>