Dub_
Dub_

Reputation: 35

JQuery / Javascript - Mouse Location completely off

I'm trying to make a 'draw' app, which allows the user to draw something by dragging their mouse over a canvas.

I want to draw a 'pixel' where the user drags their mouse, however: The location of the mouse and the location where the 'pixels' get drawn are not the same. I've searched all over the internet but I don't know what the difference is with my version and with theirs.

Image: enter image description here

HTML

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Drawer</title>
    <script src="jquery-2.2.1.min.js"></script>
    <script src="scripting/draw.js"></script>
</head>
<body>
    <canvas id="drawGround" style="width: 500px; height: 500px; margin: 0 auto; border: 1px solid black;"></canvas>
</body>
</html>

Code:

$(document).ready(function() {

  var drawSize = 3;
  var canDrawCanvas = false;
  const canvasID = "#drawGround";

  document.onmouseup = function() {
    canDrawCanvas = false;
  };

  $(canvasID).mousedown(function() {
    canDrawCanvas = true;
  });
  $(canvasID).mousemove(function(event) {
    if (canDrawCanvas) handleDrawing(event);

  });

  function handleDrawing(mouseEvent) {
    var canvas = document.getElementById(canvasID.substring(1));
    var context = canvas.getContext('2d');
    context.fillRect(mouseEvent.pageX, mouseEvent.pageY, drawSize, drawSize);
  }

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="drawGround" style="width: 500px; height: 500px; margin: 0 auto; border: 1px solid black;"></canvas>

Upvotes: 1

Views: 53

Answers (1)

SebKas
SebKas

Reputation: 554

Instead of scaling the canvas object with the "style" attribute, you should use the "width" and "height"-attributes in the canvas-element.

<canvas id="drawGround" width="500px" height="500px" style="margin: 0 auto; border: 1px solid black;"></canvas>

Then use the offsetX and offsetY parameters instead of pageX and pageY to get the tip position of the mouse:

function handleDrawing(mouseEvent) {
  var canvas = document.getElementById(canvasID.substring(1));
  var context = canvas.getContext('2d');
  context.fillRect(mouseEvent.offsetX, mouseEvent.offsetY, drawSize, drawSize);
}

Upvotes: 2

Related Questions