Search code examples
jqueryhtml5-canvasmousemovemouseclick-eventjquery-click-event

HTML5 canvas/Jquery mousemove + mouseclick event


I'm trying to get a a simple interactive cannon that moves in a 180 degree arc which follows your mouse. And then, I want it to shoot cannonballs everytime you click anywhere on screen.

I'm using HTML5 canvas and/or jquery to do the job, so far I think that I should use a mousemove event, but I'm sure if that's the simplest way. But, on the other hand I could just get my cannon rotating constantly and set up a function that will point the cannon at a set of points, then just call that function every time you move the mouse. It's a scrappy idea, but I'm just stumped otherwise.

So far I drew my cannon in canvas as shown here: http://jsfiddle.net/An3D8/1/

<canvas id="myCanvas" width="800" height="500"></canvas>
<script>
  var canvas = document.getElementById('myCanvas');
  var context = canvas.getContext('2d');
  var x = canvas.width / 2;
  var y = canvas.height / 1;
  var radius = 50;
  var startAngle = 1 * Math.PI;
  var endAngle = 2 * Math.PI;
  var counterClockwise = false;

  context.beginPath();
  context.arc(x, y, radius, startAngle, endAngle, counterClockwise);
  context.lineWidth = 15;

  // line color
  context.strokeStyle = 'black';
  context.stroke();
 </script>
<script>
  var canvas = document.getElementById('myCanvas');
  var context = canvas.getContext('2d');

  context.beginPath();
  context.rect(390, 400, 20, 70);
  context.fillStyle = 'grey';
  context.fill();
  context.lineWidth = 7;
  context.strokeStyle = 'black';
  context.stroke();
</script>

What would be the simplest way to go about having to get the cannon to follow my mouse and then shoot cannonballs?


Solution

  • Here's Cryptoburner's link applied to your canon scenario:

    http://jsfiddle.net/m1erickson/BE7F2/

    Point your canon by listening for mousemove events:

    • calculate the mouse position
    • calculate the angle of the mouse versus your canon
    • draw the canon to face the mouse position

    Example mousemove code:

    function handleMouseMove(e){
      e.preventDefault();
      e.stopPropagation();
      mouseX=parseInt(e.clientX-offsetX);
      mouseY=parseInt(e.clientY-offsetY);
      var dx=mouseX-cx;
      var dy=mouseY-cy;
      var rAngle=Math.atan2(dy,dx);
      draw(rAngle-PI/2);
    }
    

    Shoot a canon ball at the mouse position by listening for mousedown events:

    • calculate the mouse position
    • draw you canon ball as a closed arc

    Example mousedown code:

    function handleMouseDown(e){
      e.preventDefault();
      e.stopPropagation();
      mouseX=parseInt(e.clientX-offsetX);
      mouseY=parseInt(e.clientY-offsetY);
      ctx.beginPath();
      ctx.arc(mouseX,mouseY,12,0,PI*2);
      ctx.closePath();
      ctx.fillStyle="black";
      ctx.fill();
      ctx.font="14px verdana";
      ctx.fillText("Bang!",mouseX-15,mouseY-20);
    }