13

I'm trying to scale an image that has already been draw into canvas. This is the code:

var canvas = document.getElementById('splash-container');
var context = canvas.getContext('2d');
var imageObj = new Image();

imageObj.onload = function() {
  // draw image at its original size
  context.drawImage(imageObj, 0, 0);
};
imageObj.src = 'images/mine.jpeg';

// Now let's scale the image.
// something like...
imageObj.scale(0.3, 0.3);

How should I do?

Giacomo1968
  • 25,759
  • 11
  • 71
  • 103
Mich Dart
  • 2,352
  • 5
  • 26
  • 44

2 Answers2

28

You're thinking about it wrong. Once you've drawn the image onto the canvas it has no relationship to the imageObj object. Nothing you do to imageObj will affect what's already drawn. If you want to scale the image, do in the drawImage function:

drawImage(imgObj, 0, 0, imgObj.width * 0.3, imgObj.height * 0.3)

If you want to animate the scaling or are looking to achieve some other effect which requires you to draw the image at full size initially you'll have to first clear it before drawing the scaled down image.

erikvold
  • 15,988
  • 11
  • 54
  • 98
robertc
  • 74,533
  • 18
  • 193
  • 177
6

What robertc says is correct, but if you really wanted to scale an image on a canvas after drawing it for some reason, you could just scale the whole canvas using the CSS width/height properties and that would scale the image without having to redraw it.

hobberwickey
  • 6,118
  • 4
  • 28
  • 29
  • Well, I cannot scale the entire canvas because there're other objects in it, that I don't want to scale. I wanna make appear a logo on a splash screen, that should rotate and scale itself to its original size. – Mich Dart Dec 27 '12 at 13:07
  • 2
    Thanks your answer was helpful to me !! – geeky_monster Apr 05 '13 at 00:00