绘制圆圈,然后使用html canvas和javascript移动它

时间:2015-07-02 13:05:24

标签: javascript html5 canvas geometry drag

我想知道如何使用html5的画布绘制圆圈并移动它。我已经有了绘制圆形的代码,但在完成之后,我想将它拖动。我试图按照动作序列(draw - > move)来计算代码的实现,但不确定如何使用canvas和JS构建它。任何人都可以帮助我??

以下是我的代码:

HTML

<body>
  <h1>Circle</h1>
  <div class="circle">
    <canvas id="myCanvasCircle" width="500" height="500"> your browser does not support HTML5 canvas tag.</canvas>

  </div>

</body>

JS

<script>

  var canvas = document.getElementById('myCanvasCircle'),
      ctx = canvas.getContext('2d'),
      circle = {},
      drag = false;

  function draw() {
    ctx.beginPath();
    ctx.arc(circle.X, circle.Y, circle.radius, 0, 2.0 * Math.PI);
    ctx.stroke();

  }

  function mouseDown(e) {

    circle.startX = e.pageX - this.offsetLeft;
    circle.startY = e.pageY - this.offsetTop;

    circle.X = circle.startX;
    circle.Y = circle.startY;

    circle.radius = 0;

    drag = true;
  }

  function mouseUp() {
    drag = false;

  }

  function mouseMove(e) {
    if (drag) {
      circle.X = e.pageX - this.offsetLeft;
      circle.Y = e.pageY - this.offsetTop;
      circle.radius = Math.sqrt(Math.pow((circle.X - circle.startX), 2) + Math.pow((circle.Y - circle.startY), 2));
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      draw();


    }
  }

  function init() {
    canvas.addEventListener('mousedown', mouseDown, false);
    canvas.addEventListener('mouseup', mouseUp, false);
    canvas.addEventListener('mousemove', mouseMove, false);

  }

  init();

</script>

1 个答案:

答案 0 :(得分:3)

如果您只想绘制一个圆圈,修改代码就可以非常简单。

http://jsfiddle.net/15dkrakj/2/

circleMade = false;

//In mouseDown
if (!circleMade) {
    circle.radius = 0;
}

function mouseUp() {
    drag = false;
    circleMade = true;
}

//In mouseMove
if (!circleMade) {
    circle.radius = Math.sqrt(Math.pow((circle.X - circle.startX), 2) + Math.pow((circle.Y - circle.startY), 2));
}

第一次鼠标按下后,不要改变半径。

如果您希望能够绘制多个圆圈,并拖动每个圆圈......那就更复杂了。

在评论中回答问题:

http://jsfiddle.net/15dkrakj/3/

mouseMoved = false

//In mouse up
if(!mouseMoved){
    circle = {};
    circleMade = false;
    ctx.clearRect(0, 0, canvas.width, canvas.height);
}    
mouseMoved = false;

function mouseMove(e) {
    if (drag) {
        mouseMoved = true;
        ...

跟踪鼠标是否被按下并移动。如果在按下鼠标时鼠标没有移动,则在鼠标向上清除屏幕并清空圆圈。