Display image through html image element object

送分小仙女□ 提交于 2020-01-01 11:59:27

问题


I have the following code :

function createImage(source) {                
var pastedImage = new Image();                
pastedImage.onload = function() {

}
pastedImage.src = source;
}

The function createImage contain the source parameter which contain the source of an image. After that I created the object pastedImage of class Image and after alerting that I am getting the html image element object like [object HTMLImageElement].

My question is how I can display image into my html page using that object. I want to display it after onload function.

Thanks in advance.


回答1:


Hiya : Working demo http://jsfiddle.net/wXV3u/

Api used = .html http://api.jquery.com/html/

In demo click on the click me button.

Hope this helps! Please lemme know if I missed anything! B-)

Code

$('#foo').click(function() {
    createImage("http://images.wikia.com/maditsmadfunny/images/5/54/Hulk-from-the-movie.jpg");

});

function createImage(source) {
    var pastedImage = new Image();
    pastedImage.onload = function() {

    }
    pastedImage.src = source;
    $(".testimonialhulk").html(pastedImage);
}​



回答2:


Also you can do like this :

    function createImage(source) {
        var pastedImage = new Image();
        pastedImage.onload = function() {

 document.write('<br><br><br>Your image in canvas: <img src="'+pastedImage.src+'" height="100" width="200"/>');                      

        }
        pastedImage.src = source;        
    }​



回答3:


Simple, and better, using javascript dom primitive (replaceChild):

Get the parent of the image, the div or span that contains it, and replace the old img tag with the new image object you created with your function

 var domImgObj = document.getElementById("image");

 var imgObj = createImage(src); // your function
 imgObj.id = pageimgObj.id; // necessary for future swap-outs

 document.getElementById("container").replaceChild(imgObj,domImgObj);


来源:https://stackoverflow.com/questions/10876558/display-image-through-html-image-element-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!