Currently, I am engaging in a project to enhance my knowledge of node.js and html canvases.
Within my project, there is a canvas that I wish to maintain at a fixed bitmap size while occupying its containing div and preserving its aspect ratio.
I have set the canvas element size to 500x500, and then applied the following CSS style:
canvas {
display: block;
width:100%;
height:100%;
object-fit: contain;
background-color: lightgrey;
}
Initially, within the JavaScript code, I fill the canvas with white color resulting in an image like the following:
https://i.sstatic.net/eI4F7.png
By capturing mouse events, I draw lines on the canvas using a function that correctly scales the events on the canvas:
function getMousePos(evt) {
var rect = canvas.getBoundingClientRect();
var raw_x = evt.clientX || evt.touches[0].clientX;
var raw_y = evt.clientY || evt.touches[0].clientY;
var min_dimension = Math.min(rect.width, rect.height);
var x_offset = 0.5 * (rect.width - min_dimension);
var y_offset = 0.5 * (rect.height - min_dimension);
return {
x: ((raw_x - rect.left - x_offset) / min_dimension) * canvas.width,
y: ((raw_y - rect.top - y_offset) / min_dimension) * canvas.height
}
}
Although this technique works, I noticed that when drawing on the canvas and moving the mouse over a specific band on the right side, the updates are delayed until the mouse exits the band. The size of this band matches the space on the left side of the canvas, suggesting a connection that I'm unsure how to explore further. Interestingly, I do not encounter any issues when resizing the window to eliminate spaces around the canvas (enhancing performance significantly). You can view a clearer demonstration through the gif below:
https://i.sstatic.net/Zg4Qq.gif
If you have any suggestions on what might be causing this behavior or a more efficient method to achieve the same outcome, please share your insights.
Note: My browser version is Chrome 80.0.3987.149