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.
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.
4 Answers
Reset to default 4Hiya : Working demo http://jsfiddle/wXV3u/
Api used = .html
http://api.jquery./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./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);
}
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;
}
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);
document.createRange().createContextualFragment(img.outerHTML)
Example
const img = new Image()
img.src = "https://cdn.sstatic/Sites/stackoverflow/Img/favicon.ico"
const frag = document.createRange().createContextualFragment(`${img.outerHTML}`)
document.querySelector(`body`).append(frag)