Skip to content

Instantly share code, notes, and snippets.

@greggman
Last active November 18, 2025 06:53
Show Gist options
  • Select an option

  • Save greggman/93a752054633ceb12d94ce4afda05f77 to your computer and use it in GitHub Desktop.

Select an option

Save greggman/93a752054633ceb12d94ce4afda05f77 to your computer and use it in GitHub Desktop.
Canvas 2D: drawElement with save with user-zoom level undo

Canvas 2D: drawElement with save with user-zoom level undo

view on jsgist

html { font-family: monospace; font-size: 8px; background-color: #CCC;}
canvas { border: 1px solid gray; }
.test { background-color: red; color: yellow; font: initial; font-size: initial; }
.test>div {
border: 1px solid black;
}
.outer { display: inline-block; background-color: #EEE; margin: 0.5em; padding: 0.5em; }
<canvas width="64" height="64" layoutsubtree>
<div class="test">
<div style="font-size: 16px;">ThisIsIntensionallySomethingThatIsTooLong</div>
<div style="font-size: 12px;">ThisIsIntensionallySomethingThatIsTooLong</div>
<div style="font-size: 10px;">ThisIsIntensionallySomethingThatIsTooLong</div>
<div style="font-size: 8px;">ThisIsIntensionallySomethingThatIsTooLong</div>
<div>
</canvas>
const canvas = document.querySelector('canvas');
const ctx = canvas. getContext('2d');
const elem = ctx.canvas.firstElementChild;
// Make the element render at the same resolution reguardless of devicePixelRatio
elem.style.zoom = 1 / devicePixelRatio;
ctx.save()
// Expand the element so it's the same size regardless of the size it was rendered
ctx.scale(devicePixelRatio, devicePixelRatio);
ctx.drawElement(elem, 0, 0);
ctx.restore();
const saveBlob = (function() {
const a = document.createElement('a');
document.body.appendChild(a);
a.style.display = 'none';
return function saveData(blob, fileName) {
const url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
};
}());
canvas.toBlob((blob) => saveBlob(blob, 'canvas-64x64-with-adjustment.png'));
{"name":"Canvas 2D: drawElement with save with user-zoom level undo","settings":{},"filenames":["index.html","index.css","index.js"]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment