Responsive Canvas | Sololearn: Learn to code for FREE!

+6

Responsive Canvas

How can I make canvas responsive?

7/4/2021 5:20:48 AM

Smart Potato

9 Answers

New Answer

+7

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(); }

+3

Thank you everyone 🤩

+2

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

+2

Window.innerWidth

+2

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 ;)

+2

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

+2

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

+2

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

+1

visph Ohhh, that is a bit difficult 🙁