0

I want users to upload an image or specify a URL of an image and then be able to look like they're drawing on top of the image. So I can make a <canvas> element with a background image. But I don't know beforehand how big that image is (well I can figure it out if they uploaded an image). How can I deal with this using jQuery?

I know I can call $('img#id_name').width and create a canvas based on that width (and get the height the same way). But I want that to be the background image.

at.
  • 50,922
  • 104
  • 292
  • 461

1 Answers1

0

You can get image's original width/height values after loading and than use css() method for defining values.

var img = $('img#id_name')[0]; // Get my img elem
var pic_real_width, pic_real_height;
$("<img/>") // Make in memory copy of image to avoid css issues
    .attr("src", $(img).attr("src"))
    .load(function() {
        iWidth = this.width;   // Note: $(this).width() will not
        iHeight = this.height; // work for in memory images.

   $('#canvasEle').css({'width': iWidth + 'px', 'height': iHeight + 'px'});
});

Calculating image source.

Community
  • 1
  • 1
Barlas Apaydin
  • 7,233
  • 11
  • 55
  • 86
  • Note that this code should go into the onload event handler for the image, because you don't know the size until the image has loaded. – Philipp Jan 12 '13 at 18:51
  • This code looks right, except that I wanted the size of the background image: `
    `
    – at. Jan 14 '13 at 21:38