HTML5 JS fillRect () weird behavior

I have two odd problems with fillright (x, y, width, height).

  • Increases height by two

  • It is assumed that X and y should be set to the mouse position, but the rectangle is turned off in the lower left corner and goes further when the mouse moves to the lower left position.

This code is from a video tutorial, and this code seems to work for the guy and the video, and everyone else, since no one has commented on this problem. Anyway, here is the code:

function doFirst(){ canv = document.getElementById('canvas'); canvas = canv.getContext('2d'); document.addEventListener("mousemove", onMouseMove, false); } function onMouseMove(e){ canvas.clearRect(0, 0, canv.width, canv.height); var x = e.clientX; var y = e.clientY; canvas.fillRect(x, y, 50, 50); } window.addEventListener("load", doFirst, false); 

I thought that maybe I skipped a step in the tutorial, and after checking again and again, I decided to simplify it by just drawing a rectangle without a mouse listener, but the canvas still painted it with a height of 2X and about 2x y position.

 function doFirst(){ canv = document.getElementById('canvas'); canvas = canv.getContext('2d'); canvas.fillRect(10, 10, 50, 50); } window.addEventListener("load", doFirst, false); 

The fillRect function only worked fine the other day when I first started playing with an HTML5 canvas, so what happened? how did i break it?

+1
source share
1 answer

I believe this is because you are trying to set the width and height of the canvas using CSS:

 <!--Sets size of the canvas on the page--> <canvas id="canvas" style="width:500px; height:500px;"></canvas> 

Use this instead:

 <!--Sets drawing surface size--> <canvas id="canvas" width="500" height="500"></canvas> 

The attributes "width" and "height" indicate the size of the surface of the drawing, which by default is 300x150. Setting the CSS width and height for the canvas will expand or reduce the drawing surface, but will not change the number of pixels on the surface. fillRect takes the coordinates in pixels of the "drawing", not the "pixels of the HTML page".

+10
source

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


All Articles