Skip to content Skip to sidebar Skip to footer

How To Draw Circle Centered At Mouse Location When A Key Is Pressed

I am trying to change this jQuery code slightly: jQuery(document).ready(function(){ $('#canvas').attr('height', $('#canvas').css('height')); $('#canvas').attr('width', $('#canvas')

Solution 1:

The main problem here is that you can't focus on a canvas and without focus, it doesn't take keyboard input. Instead, setup a keypress listener on the document and check if you're over the canvas.

jQuery(document).ready(function() {
  $('#canvas').attr('height', $('#canvas').css('height'));
  $('#canvas').attr('width', $('#canvas').css('width'));
  var x = -1;
  var y = -1;

  // Make sure the mouse is over the canvasvar overCanvas = false;
  $('#canvas').mouseover(function() {
    overCanvas = true;
  });
  $('#canvas').mouseleave(function() {
    overCanvas = false;
  });
  $("#canvas").mousemove(function(e) {
    // Use offset[X/Y] instead of page[X/Y]// page[X/Y] will only be accurate if the canvas// takes up the whole page
    x = e.offsetX;
    y = e.offsetY;
  });
  $(document).keypress(function(e) {
    if (!overCanvas) {
      return;
    }
    var canvas = $('#canvas')[0];
    var ctx = canvas.getContext("2d");
    ctx.strokeStyle = '#FFF'; // Stroke in white
    ctx.beginPath();
    ctx.arc(x, y, 5, 0, 2 * Math.PI);
    ctx.stroke();

    $('#status').html(x + ', ' + y);
  });

})
canvas {
  display: block;
  background: #000;
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><canvasid="canvas"width="320"height="240"></canvas><spanid="status"></span>

Post a Comment for "How To Draw Circle Centered At Mouse Location When A Key Is Pressed"