Skip to content

Instantly share code, notes, and snippets.

@edew
Last active December 21, 2022 15:36
Show Gist options
  • Save edew/c7b2bfd68ae9afcf7732a50522706a76 to your computer and use it in GitHub Desktop.
Save edew/c7b2bfd68ae9afcf7732a50522706a76 to your computer and use it in GitHub Desktop.
Rescaling Canvas to Parent Element Size
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<style>
html, body {
margin: 0;
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
const canvasElement = document.getElementById('canvas');
const c = canvasElement.getContext('2d');
let rafPending = false;
const raf = (f) => {
if (rafPending) {
return;
}
rafPending = true;
window.requestAnimationFrame(() => {
rafPending = false;
f();
});
};
const setCanvasSizeFromParent = () => {
const dpr = window.devicePixelRatio || 1;
const w = c.canvas.parentElement.clientWidth * dpr;
const h = c.canvas.parentElement.clientHeight * dpr;
c.canvas.width = w;
c.canvas.height = h;
c.canvas.style.width = `${w}px`;
c.canvas.style.height = `${h}px`;
c.scale(dpr, dpr);
c.beginPath();
c.moveTo(0, 0);
c.lineTo(c.canvas.width, c.canvas.height);
c.stroke();
};
window.addEventListener('resize', () => {
raf(setCanvasSizeFromParent);
});
raf(setCanvasSizeFromParent);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment