dhotson/springy

Sizing Canvas in CSS does not work

thurt opened this issue · 2 comments

thurt commented

It seems that I can only change a graph's size by specifying a width and a height attribute in the canvas html tag. When I try to specify a width or height for the canvas tag with CSS the result is a stretched graph that makes all the graph items look larger rather than providing extra space.

I'm also interested in having the ability to resize the canvas tag dynamically (such as when the browser window size changes).

Do you have any suggestions for how to fix this issue? Thanks

Ah yep, I’ve come across this before. :)

A canvas is a 2d grid of pixels and the resolution is controlled by the width and height attributes in the canvas html.
Applying a CSS width and height won’t change the resolution of the canvas element—it just changes the visual size i.e. making it blurry.

To make this work properly, you'll need to hook into the window onresize event and update the attributes of the canvas element. Hope that helps! :)

thurt commented

Thanks for the quick reply dhotson.

Applying a CSS width and height won’t change the resolution of the canvas element—it just changes the visual size

This is a good point I missed. I haven't worked with canvas much before so this one got me. I wonder why CSS cannot also trigger a resolution change like the HTML attributes?

So I just tried resizing like this:

$('#graph').click(function() { $(this).width('400px') })

and like this:

$('#graph').click(function() { $(this).attr('width','400px') })

Sure enough, the second routine does not stretch pixels.

In case anyone comes looking, here is a script in vanilla js for resizing the canvas on window resize. This is a boiled-down version from the article: http://htmlcheats.com/html/resize-the-html5-canvas-dyamically/

(function() {
  var canvas = document.getElementById('your-canvas-id')
  window.addEventListener('resize', resizeCanvas, false)
  resizeCanvas()

  function resizeCanvas() {
    canvas.width = /* window.innerWidth or another container width */
    canvas.height = /* window.innerHeight or another container height */
  }
})()