Did this meet your expectations?
This revised code snippet adjusts the canvas size to match the smaller dimension of the window (width or height) whenever the window is resized. It also ensures that the canvas is displayed as a block element and centered using margin: 0 auto.
Feel free to check out the live demo.
UPDATE 1: I have made modifications with explanatory comments on where you can customize the code to resize the canvas based on the larger dimension between window height and width.
UPDATE 2: The code has been optimized to center the crosshairs on the canvas by adjusting the dimensions to perfectly fit the window size.
In addition, the CSS has been updated to eliminate any padding and margins within the canvas area.
The canvas content gets redrawn upon window.onresize
event trigger.
var canvas = document.createElement('canvas');
document.body.appendChild(canvas);
function setSize() {
var w = window.innerWidth;
var h = window.innerHeight;
// Resize canvas based on largest dimension
//var size = (h > w) ? h : w;
//var size = (h < w) ? h : w;
//canvas.width = size;
//canvas.height = size;
// Exact resizing to match width and height
canvas.width = w;
canvas.height = h;
}
function draw() {
var context = canvas.getContext('2d');
context.fillRect(0, 0, canvas.width, canvas.height);
context.strokeStyle = 'red';
context.moveTo(canvas.width / 2, 0);
context.lineTo(canvas.width / 2, canvas.height);
context.moveTo(0, canvas.height / 2);
context.lineTo(canvas.width, canvas.height / 2);
context.stroke();
}
setSize();
draw();
window.onresize = function (e) {
setSize();
draw();
};
* {
padding: 0;
margin: 0;
}
canvas {
display: block;
margin: 0 auto;
}