3

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";
Someone2088
  • 141
  • 2
  • 7
  • 16

3 Answers3

4

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

Community
  • 1
  • 1
CupawnTae
  • 14,192
  • 3
  • 29
  • 60
2

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";
jazzytomato
  • 6,994
  • 2
  • 31
  • 44
0

drawImage() takes additional width and height parameter:

   context.drawImage(image, x, y, width, heighT)

https://duckduckgo.com/?q=!mdn+drawimage

Mikko Ohtamaa
  • 82,057
  • 50
  • 264
  • 435