Moving canvas shapes with mouse - Javascript Canvas

Javascript examples for Canvas:Mouse

Description

Moving canvas shapes with mouse

Demo Code

ResultView the demo in separate window

<!doctype html>
<html>
   <head> 
      <!-- reset css --> 
      <script type="text/javascript" src="https://code.jquery.com/jquery.min.js"></script> 
      <style>

body{ background-color: ivory; }
#canvas{border:1px solid red;}

      </style> 
      <script>
$(function(){/* w ww . ja va  2s  .com*/
    // get references to the canvas and its context
    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    var $canvas=$("#canvas");
    var canvasOffset=$canvas.offset();
    var offsetX=canvasOffset.left;
    var offsetY=canvasOffset.top;
    var scrollX=$canvas.scrollLeft();
    var scrollY=$canvas.scrollTop();
    ctx.lineWidth=3;
    var circles=[];
    var selectedCircle=-1;
    var $create=$("#rCreate")[0];
    var $select=$("#rSelect")[0];
    var $move=$("#rMove")[0];
    function drawAll(){
        ctx.clearRect(0,0,canvas.width,canvas.height);
        for(var i=0;i<circles.length;i++){
            var c=circles[i];
            ctx.beginPath();
            ctx.arc(c.cx,c.cy,c.radius,0,Math.PI*2);
            ctx.closePath();
            ctx.fillStyle=c.color;
            ctx.fill();
            // if this is the selected circle, highlight it
            if(selectedCircle==i){
                ctx.strokeStyle="red";
                ctx.stroke();
            }
        }
    }
    function handleMouseDown(e){
      e.preventDefault();
      mouseX=parseInt(e.clientX-offsetX);
      mouseY=parseInt(e.clientY-offsetY);
      if($create.checked){
          circles.push({cx:mouseX,cy:mouseY,radius:10,color:randomColor()});
          selectedCircle=circles.length-1;
      }
      if($select.checked){
          selectedCircle=-1;
          for(var i=0;i<circles.length;i++){
              var c=circles[i];
              var dx=mouseX-c.cx;
              var dy=mouseY-c.cy;
              var rr=c.radius*c.radius;
              if(dx*dx+dy*dy<rr){ selectedCircle=i; }
          }
      }
      if($move.checked && selectedCircle>=0){
          var c=circles[selectedCircle];
          c.cx=mouseX;
          c.cy=mouseY;
      }
      drawAll();
    }
    function randomColor(){
        return('#'+Math.floor(Math.random()*16777215).toString(16));
    }
    $("#canvas").mousedown(function(e){handleMouseDown(e);});
}); // end $(function(){});

      </script> 
   </head> 
   <body> 
      <input type="radio" name="grp1" id="rCreate" checked>
      Click will create a new circle.
      <br> 
      <input type="radio" name="grp1" id="rSelect">
      Click will select an existing circle.
      <br> 
      <input type="radio" name="grp1" id="rMove">
      Click will move selected circle.
      <br> 
      <canvas id="canvas" width="300" height="300"></canvas>  
   </body>
</html>

Related Tutorials