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

Display image through html image element object

本文关键字:图像 显示 显示图 对象 图像元 html 通过 元素      更新时间:2023-09-26

我有以下代码:

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

该函数createImage包含包含图像源的源参数。之后,我创建了类 Image 的对象pastedImage,并在提醒我正在获取像 [object HTMLImageElement] 这样的 html 图像元素对象之后。

我的

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

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

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

在演示中,单击click me按钮。

希望这有帮助!如果我错过了什么,请告诉我!B-)

法典

$('#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);
}​
你也可以

这样做:

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

简单,更好,使用 javascript dom primitive (replaceChild):

获取图像的父级、包含它的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);

document.createRange().createContextualFragment(img.outerHTML)

const img = new Image()
img.src = "https://cdn.sstatic.net/Sites/stackoverflow/Img/favicon.ico"
const frag = document.createRange().createContextualFragment(`${img.outerHTML}`)
document.querySelector(`body`).append(frag)