As mentioned in this response, it appears that disabling page zooming is not achievable, which is acceptable. Instead, a more practical approach would be to adjust the canvas size to accommodate the current page zoom level (or maintain a consistent canvas size).
Implementing this is straightforward, simply incorporate window.devicePixelRatio
into your canvas resizing calculations.
When there is no page zoom, the window.devicePixelRatio
variable holds a value of 1
and adjusts accordingly with each zoom operation to reflect the current zoom percentage.
For instance, to always align with window dimensions, use:
function resizeToWindow() {
canvas.width = window.innerWidth * window.devicePixelRatio;
canvas.height = window.innerHeight * window.devicePixelRatio;
}
To match the size of the parent container, utilize:
function resizeToParent() {
canvas.width = canvas.clientWidth * window.devicePixelRatio;
canvas.height = canvas.clientHeight * window.devicePixelRatio;
}
Apply these or similar styles:
canvas {position: absolute; top: 0; left: 0; width: 100%; height: 100%}
The optimal approach to determine when to invoke the above functions and perform resizing is by leveraging requestAnimationFrame
to compare the current canvas dimensions and devicePixelRatio
value with those from the previous frame (conduct the comparison per frame but only resize if necessary).
Alternatively, consider utilizing the ResizeObserver API for more precise dimension retrieval through the devicePixelContentBoxSize
property, although browser support for this feature remains quite limited at present.