Why don't the rectangles that I create on this canvas get to the right place?

I am trying to create a simple page on which you click and can create rectangles on the canvas. As input, user clicks are entered, and then a rectangle is created from the x and y clicks. However, it puts the rectangle aside for some amount, and I'm not sure why.

Fiddle: https://jsfiddle.net/2717s53h/

HTML

<canvas id="cnv"></canvas> 

CSS

 #cnv{ width:99vw; height:98vh; background-color:#faefbd; } 

JAVASCRIPT

 $(function () { var canvas = $('#cnv'); var canvObj = document.getElementById('cnv'); var ctx = canvObj.getContext('2d'); var point1 = {}; var point2 = {}; canvas.click(function (e) { console.log(e); var x = e.pageX; var y = e.pageY; console.log(x); console.log(y); if (Object.keys(point1).length == 0) { point1.x = x; point1.y = y; } else if (Object.keys(point2).length == 0) { point2.x = x; point2.y = y; console.log(point1); console.log(point2); var width = point2.x - point1.x; var height = point2.y - point1.y; width = width < 0 ? width * -1 : width; height = height < 0 ? height * -1 : height; ctx.fillRect(x, y, 10, 10); point1 = {}; point2 = {}; } }); }); 
+5
source share
1 answer

There is a difference between the height and width of the CSS height and the attributes of the HTML canvas: the first defines the space that the canvas occupies on the page; the latter defines the rendering surface. In concreto, suppose you have the following canvas:

 <canvas height="400" width="600"></canvas> 

with a window size of 1200x800, and the "CSS" canvas is set to width: 100%; height: 100%; width: 100%; height: 100%; , then your canvas will appear as stretched twice as large and blurred in height and width (for example, in your violin, these rectangles are clearly more than 10 pixels). As a result, page coordinates are not synchronized with canvas coordinates .

According to the specification, your canvas rendering surface will be 300x150 because you did not specify width / height attributes:

The default width attribute is 300, and the default height attribute is 150.

Check out the slightly “fixed” version of your script .

As a result, my advice (as a non-specialist on HTML canvas) should always indicate these 2 attributes and not interfere with different sides of rendering and display (of course, not relative such as vw, vh,%, em, ...) if You do not want unpredictable results; although some SO users were looking for a solution .

+3
source

Source: https://habr.com/ru/post/1233810/


All Articles