Reputation: 141
I am trying to draw a few .png images to the HTML5 canvas using JavaScript. I currently have a function that will draw an image to the canvas, but the image is too large for the canvas, so only part of it displays.
The function I currently have is:
function drawImage(x, y){
var numberImage = new Image();
numberImage.src = imageSource;
context.drawImage(numberImage, x, y);
}
and I call the function by using:
var image1 = new Image();
image1.onLoad = function(){
context.drawImage(image1, 50, 50);
};
image1.src="1.png";
I was just wondering if anyone knows of a way of resizing an image when it's drawn to the canvas, so that I could just a thumbnail sized image?
Thanks in advance!
I have tried adding parameters in to the drawImage function to resize the image, but this doesn't seem to have made any difference...
var image1 = new Image();
image1.onLoad = function(){
context.drawImage(image1, 50, 50, 10, 10);
};
image1.src="1.png";
Upvotes: 3
Views: 6818
Reputation: 14580
Are you using CSS to set the size of the canvas? You need to set a height and width on the element instead or everything in your canvas will be scaled "unexpectedly". This could be your problem.
See Strange HTML5 Canvas drawImage behaviour
Upvotes: 4
Reputation: 7214
I had trouble finding the problem in your code... But I found it !
You gonna hate this : you wrote image.onLoad instead of image.onload... yes, javascript is case-sensitive. :-)
correct code is :
var image1 = new Image();
image1.onload = function(){
context.drawImage(image1, 50, 50, 10, 10);
};
image1.src="1.png";
Upvotes: 2
Reputation: 83348
drawImage() takes additional width and height parameter:
context.drawImage(image, x, y, width, heighT)
https://duckduckgo.com/?q=!mdn+drawimage
Upvotes: 0