Responsive Web Design (How To: Fit Canvas to a DIV's Width & Height)

I’m attempting to position a canvas inside of a specific div. I also want that canvas to resize responsively to the size of that div.

I’ve seen examples online for tying the position of the canvas to a div and then using the windowWidth & Height… but that only sizes according to the window size.



  • See this demo of a straightforward solution ;)

    Source code

    What you're interested in is the CSS; and it's very simple. Set the sketch canvas width to %100; the canvas height to auto and it will then fill whatever container it's placed within; be that the whole window or a specified div... BUT in order to be responsive the container div itself has to be responsive - i.e. its dimensions should probably be set as percentages (e.g. in the above demo try changing #sketch01 width to 50%; or you can fix the size and change it using media queries...

    Note that this in no way changes the size the sketch is actually being rendered at: that's fixed to 600 x 600 - which is then stretched/shrunk to fill the container. That has pros and cons: the main pro is that it's simple. The main cons are that it may not look so good if it's stretched too far above that size; and it's unnecessarily using resources if it's shrunk too far below...

  • @blindfish Thanks that's exactly what I was looking for. I appreciate your help!

Sign In or Register to comment.