I want an html canvas to have a background image and I want my drawing on that background image to maintain its location when I resize the image. I also want the canvas to take up the entire screen. I can keep the canvas drawing in line with the background image when the canvas's height is the same as the background image's calculated height. But when the canvas is full screen size, resizing the canvas smushes the drawing, and it doesn't stay in line with the background image.
canvas doesn't line up with background image when canvas.style.height is 100%
canvas does stay in line with the background image, but the canvas is not full size
And here's the code used for the resize event handler:
const onResize = () => {
let backgroundImageWidth, backgroundImageHeight;
const backgroundImageSource = document.querySelector("#responsive-canvas")
.style.backgroundImage;
const problemBackgroundImage = new Image();
problemBackgroundImage.onload = function () {
let aspect_ratio = this.width / this.height;
backgroundImageWidth = 0.45 * window.innerWidth;
backgroundImageHeight = backgroundImageWidth / aspect_ratio;
const calculatedHeight = window.innerWidth / aspect_ratio;
let img = document.createElement("img");
img.src = dataURL; // dataURL is the value of canvas.toDataURL()
canvas.width = window.innerWidth;
canvas.height = calculatedHeight;
canvas.style.height = calculatedHeight; // commenting out this line gives me the fullsize canvas, but the drawing does not line up.
img.onload = function () {
context.drawImage(img, 0, 0, canvas.width, canvas.height);
context.restore();
};
};
};