javascript 通过html图像元素对象显示图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10876558/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 11:19:47  来源:igfitidea点击:

Display image through html image element object

javascriptjqueryjavascript-events

提问by J.K.A.

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].

函数 createImage 包含包含图像源的源参数。之后,我创建了 Image 类的对象 pasteedImage 并在警告我正在获取 html 图像元素对象后,如[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.

我的问题是如何使用该对象将图像显示到我的 html 页面中。我想在 onload 功能后显示它。

Thanks in advance.

提前致谢。

采纳答案by J.K.A.

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;        
    }?

回答by Tats_innit

Hiya : Working demohttp://jsfiddle.net/wXV3u/

Hiya:工作演示http://jsfiddle.net/wXV3u/

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

使用的 API = .htmlhttp://api.jquery.com/html/

In demo click on the click mebutton.

在演示中单击click me按钮。

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);
}?

回答by Mark Bordelon

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

使用 javascript dom 原语 (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

获取图像的父级、包含它的 div 或 span,并将旧的 img 标记替换为您使用函数创建的新图像对象

 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);