Resize Canvas | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Resize Canvas

I'm trying to make a project using canvas, but I can't seem to resize the canvas using %. If I do it in HTML the canvas resizes with pixels. In CSS the quality of the canvas is lowered. In JavaScript it just breaks the canvas. How can I resize the canvas depending on the users screen without lowering the canvas quality? https://code.sololearn.com/WAYQeutAfeXe/?ref=app

27th Dec 2017, 11:42 PM
MemeSenpai
MemeSenpai - avatar
1 Answer
+ 5
Run this to watch how CSS and HTML canvas scaling properties interact: https://code.sololearn.com/WETCkRaPNVhy/?ref=app I'm using pixels. To calc by "viewport" using "vh" and "vw" for percentage of viewport height and width: Line 28... let's use 50, to test scaling up to 50% of the user's view: var maxOuterDimension = 50; // was 200 for use as pixels Lines 67-68, change the units from "px" to viewport-relative height / width: theCanvas.style["height"] = cvsContainerHeight + "vh"; // was 'px' theCanvas.style["width"] = cvsContainerWidth + "vw"; // was 'px' And run. The units are required when setting styles this way (the engine does weird things if you omit them).
27th Dec 2017, 11:52 PM
Kirk Schafer
Kirk Schafer - avatar