GreenFerret95
GreenFerret95

Reputation: 117

Javascript How to change height and width of an image src

I'm trying to do something very simple. I want to take an image from a document. Draw it to the screen. And be able to resize this image's height and width to what ever I choose. What I have now doesn't change the size at all. What am I doing wrong? I don't want to use anything but Javascript for this.

var ctx = document.getElementById('mycanvas').getContext('2d');
var img = new Image();

function draw(){
    img.onload = function(){
    ctx.drawImage(img,100,100);
    };

img.style.height = '300px';
img.style.width = '300px';
img.src = "test.png";
}

draw();

Upvotes: 0

Views: 1327

Answers (1)

markE
markE

Reputation: 105035

context.drawImage has additional arguments that do the resizing for you:

var img=new Image();
img.onload=function(){
    var scaleFactor=2.00;
    ctx.drawImage(
        img,
        100,100,
        img.width*scaleFactor,img.height*scaleFactor
    );    
}
img.src='test.png'

Upvotes: 1

Related Questions