I think this is the behavior you are trying to achieve. I refactored it so you only need to create one Image
object (and changed the variable names to English so I could follow the code easier). Hopefully it's clear how the code works. Feel free to ask in the comments if you have any questions about it. The body onload property will need to be changed to "setupBackground();"
instead of "draw();"
to work with this code.
function setupBackground() {
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
function draw() {
canvas.width = 0;
canvas.height = 0;
var divHeight = div.scrollHeight;
var divWidth = div.scrollWidth;
var yScale = divHeight / img.height;
var xScale = divWidth / img.width;
var newImgHeight = img.height * xScale;
var newImgWidth = divWidth;
if (divHeight >= newImgHeight) {
newImgHeight = divHeight;
newImgWidth = img.width * yScale;
}
canvas.width = divWidth;
canvas.height = divHeight;
ctx.drawImage(img,0,0,newImgWidth,newImgHeight);
}
var img = new Image();
img.onload = function() {
window.onresize = draw;
draw();
}
img.src = 'ad.jpg';
};