Jump to content

50px not 50px in canvas?


astralaaron

Recommended Posts

I've been trying to draw out some lines X amount of pixels and I just can't get it right.  For example here on the following jsFiddle I am trying to draw out lines 50px apart.  When I console log the X position it logs 50, 100, 150, 200, etc. but when you measure the lines with a browser extension ruler and also with the X position that I am outputting on the page you can see they are not 50px apart.  It will be more like 50, 98, 146, etc.

I understand canvas calculates pixels from the center of the pixel and I've tried adding 0.5 to the position and also subtracting but it didn't seem to make any difference.

https://jsfiddle.net/4y0q2pdw/33/

Been stuck for days, any suggestions appreciated!

Link to comment
Share on other sites

The size of pixels on the canvas is different than the size of pixels in the browser. By default, they're the same, but if you resize the canvas with CSS they change.

If you have <canvas width="100" height="100"> and you use CSS to set its width to 200px, then each pixel on the canvas will occupy two pixels on the page. The width and height attribute of the canvas indicate the size of the surface being drawn on.

Link to comment
Share on other sites

18 hours ago, Ingolme said:

The size of pixels on the canvas is different than the size of pixels in the browser. By default, they're the same, but if you resize the canvas with CSS they change.

If you have <canvas width="100" height="100"> and you use CSS to set its width to 200px, then each pixel on the canvas will occupy two pixels on the page. The width and height attribute of the canvas indicate the size of the surface being drawn on.

Thank you so much, this was exactly the problem.  I was setting the height of the canvas in CSS and it was scaling the pixels.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...