Resizing the canvas, where is the problem?
I'll post a link from then on to write here:
http://hem.bredband.net/noor/canvas.htm
My goal is to make the image fit inside the window, with the width of the image being the same as the window, even after resizing. If the height of the image becomes large for the window, then the image should resize according to the height, not the width.
Somewhere in my code there is something wrong .. sorry if this is stupid, I am still learning.
Thanks!
a source to share
I think this is the behavior you are trying to achieve. I refactored it so you only need to create one object Image
(and changed the variable names to English so I can follow the code better). Hope it's clear how the code works. Feel free to ask in the comments if you have any questions about this. For this code to work, the body's onload property must be replaced with "setupBackground();"
instead "draw();"
.
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';
};
a source to share