Question

I am trying to give height to an image object using javascript, But its not working.

html code

 <canvas id="canvas1" height="500px" width="500px">

 </canvas>

I want to create background image using javascript and this image must be set according to canvas size.

Javascript code:

canvas = document.getElementById("canvas1");
c = canvas.getContext("2d");
var bg = new Image();
bg.src = "images/bg.png";
bg.height = "100";
bg.width = "100";
c.drawImage(bg,0,0);

I can see the image but can not give the height and width of that image at run time.
How can i give the height and width of image object at runtime.?
Thank you in advance for your help.

Was it helpful?

Solution

There are a few issues in the code:

Issue 1

The first one being the tag attributes. Doesn't really affect the result but the correct syntax is an integer value without px at the end as width and height for canvas can only use pixels:

<canvas id="canvas1" height="500" width="500"></canvas>

Issue 2

The next issue is that you try to set read-only properties on the image element:

var bg = new Image();
bg.src = "images/bg.png";
//bg.height = "100";      invalid
//bg.width = "100";       invalid

You don't really need to set the image size; you can if you absolutely want by using this syntax (then get actual size using naturalWidth / naturalHeight if you should need them later - the full image will be loaded in any case):

var bg = new Image(width, height);

But you can simply use width and height with the drawImage() method (see below).

Issue 3

The third issue is that you don't allow the image to load. Image loading is asynchronous so you need to add an onload handler:

var bg = new Image();
bg.onload = done;         /// wait for image to load, then call done()
bg.src = "images/bg.png";

function done() {
    c.drawImage(bg,0,0);
    /// continue here
}

Optionally define the destination size like this:

function done() {
    c.drawImage(bg,0,0, width, height);  /// the size you want
    /// continue here
}

If you want to fill the canvas use:

c.drawImage(bg,0,0, canvas.width, canvas.height);

Hope this helps!

OTHER TIPS

Since it's on a canvas you need to set them in the drawimage function

canvas = document.getElementById("canvas1");
c = canvas.getContext("2d");
var bg = new Image();
bg.src = "images/bg.png";
c.drawImage(bg,0,0, 100, 100);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top