user2585578
user2585578

Reputation: 415

draw circle and then move it around using html canvas and javascript

I would like to know how to draw a circle using html5's canvas and move it around. I already have the code for drawing a circle, but after that is finished, I want to drag it around. I was trying to figure the implementation of the codes following the sequence of actions (draw --> move), but not sure how to build it using canvas and JS. Anybody can help me??

Below is my code:

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>

Upvotes: 0

Views: 5510

Answers (1)

Devin H.
Devin H.

Reputation: 1105

If you want to draw just one circle, it's fairly simple to modify your code to do it.

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));
}

Just don't change the radius after the first mouse down and up.

If you're wanting to be able to draw multiple circles, and drag each one... that's a bit more complicated.

To answer question in comments:

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;
        ...

This tracks whether the mouse was pressed down and moved. If the mouse isn't moved while it's pressed down, on mouse up clear the screen and empty the circle.

Upvotes: 3

Related Questions