Responsive Canvas | Sololearn: Learn to code for FREE!


Responsive Canvas

How can I make canvas responsive?

7/4/2021 5:20:48 AM

Smart Potato

9 Answers

New Answer


Use fixed width and height for your buffer canvas where you draw everything, calculate ratio and then draw to visible fullscreen canvas with keeping same ratio const [W,H] = [300,600]; const ratio = W/H; const bufferCanvas = document.createElement("canvas"); bufferCanvas.width = W; bufferCanvas.height = H; const buffer = bufferCanvas.getContext("2d"); const canvas = document.createElement("canvas"); const ctx = canvas.getContext("2d"); document.body.appendChild(canvas); addEventListener("resize", () => fitCanvas(innerWidth, innerHeight)); function render() { ctx.drawImage(bufferCanvas, 0, 0, canvas.width, canvas.height); } function fitCanvas(w,h) { if(w/h > ratio) { resize(w, w / ratio); } else { resize(h * ratio, h); } } function resize(w,h) { canvas.width = w; canvas.height = h; render(); }


Thank you everyone 🤩


that's quite tricky ;P you must resize the canvas dimensions as soon as viewport get resized and redraw its content accordingly ^^




yes, and you should define how the redrawn is handled: roughly responsive or not... but canvas size must have dimensions (in pixel) very differents... that's why usually canvas is used with fixed dimensions ;)


Canvas.width = window.innerWidth Canvas.height = window.innerHeight


Sofi (DM❌) only if you define canvas css dimensions to fit viewport ^^ anyway, with big sized viewports, high sized canvas would be less efficient: it could be smart to have canvas size reduced related to viewport size ;P


window. onresize=function(){ canvas.height=window. inneHeight canvas.width=window.innerWidth }


visph Ohhh, that is a bit difficult 🙁