首页 > 解决方案 > 如何使画布中的圆形对象可移动

问题描述

我正在尝试让圆形对象移动,就像鼠标点击时移动一样,当鼠标离开时它会停止。单击时圆圈正在移动,但问题是创建了很多圆圈。我只想在画布上画一个圆圈。

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>

标签: javascriptcanvashtml5-canvas

解决方案


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


推荐阅读