Jump to content
Sign in to follow this  
astralaaron

50px not 50px in canvas?

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!

Share this post


Link to post
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.

Share this post


Link to post
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.

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
Sign in to follow this  

×
×
  • Create New...