The <img/> tag is part of HTML, as you've already known from your previous studies in web technologies. :) You can create one programmatically with the Image object in JavaScript. See below:
var img = new Image();
Try to log it to the console. Right know, it's empty. To load an image, use the src tag:
var img = new Image(); // of course, don't forget to replace this url ;) img.src = 'http://www.testsite.com/images/myimage.jpg';
The image is loaded, but you can't see it yet, because it isn't appended to the DOM. Let's use jQuery to do what is needed to do!
jQuery('#myDiv').html(img);
The image is visible right know. This JavaScript object has another property called onload. It fires when the image is loaded. Append these few lines after your code and refresh your page:
img.onload = function() { alert('image loaded'); }
In Internet Explorer, the onload function won't run, unless you place it before the definition of src attribute:
var img = new Image(); img.onload = function() { alert('image loaded'); } img.src = 'http://www.mysite.com/images/an_image.jpg';
Go and have some fun with the onerror attribute! It runs when an error occurs while loading an image.
var img = new Image(); img.onerror = function() { alert('failed to load image :( '); } img.src = 'http://www.fakelink.com/images/non_existing_image.png';
Canvas element and Javascript drawImage function
Another way to use the image object is to draw it with the help of the canvas element. First, have one in your example html page:<canvas id="myCanvas" width="400" height="300"></canvas>
Then, get the canvas and a context and use drawImage function.
var canvas = $("#myCanvas"); /* For browser compatibility issues, put error handling code here. I won't.. */ var ctx = canvas[0].getContext('2d'); var img = new Image(); img.src = 'http://static.yoursite.com/images/something.png'; ctx.drawImage(img, 0, 0);
The first parameter of the drawing function is the image object itself. The second and third parameters are for placing the image along the x and y coordinates. Note that the (0, 0) coordinate is the top left corner. Also note that canvas element is not supported yet in Internet Explorer.
That's all for today of the JavaScript Image object and its usage. I will tell more about the drawImage function in another post where I will talk about sprites, animation and a bit more JavaScript tricks. I hope you learned a little new today.
good work.
ReplyDeleteJavascript training in chennai