Display image through html image element object - javascript

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.

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

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.net/Sites/stackoverflow/Img/favicon.ico"
const frag = document.createRange().createContextualFragment(`${img.outerHTML}`)
document.querySelector(`body`).append(frag)

Related

Image Swap on MouseOut (JavaScript, not JQ)

I am trying to create functions to mouseover and mouseout of images. The tricky part is this function needs to work for any image, and I cannot use direct image names. I have to therefore use variables.
The HTML code is as follows for the images:
The HTML for the images is like this, and there are 3 images:
<img src="images/h1.jpg" alt="" id="images/h4.jpg" onmouseover="swapToNewImage(this)" onmouseout="swapImageBack(this)">
I'm expecting that you have to reference the id for the new image, and then the src attribute for the previous image to revert when you mouseout.
The problem is that, if I reference the id attribute, the image no longer has information on the src attribute so I cannot call it to revert back.
Here is the JavaScript I have thus far. It works to swap the image to a new one, but not to swap it back :(
//FUNCTION
var $ = function (id) {
return document.getElementById(id);
}
//ONLOAD EVENT HANDLER
window.onload = function () {
//GET ALL IMG TAGS
var ulTree = $("image_rollovers");
var imgElements = ulTree.getElementsByTagName("img");
//PROCESS EACH IMAGE
//1. GET IMG TAG
for (var i = 0; i < imgElements.length; i++) {
console.log (imgElements[i]);
console.log (imgElements[i].getAttribute("src"));
//2. PRELOAD IMAGE FROM IMG TAG
var image = new Image();
image.setAttribute("src", imgElements[i].getAttribute("src"));
//3. Mouseover and Mouseout Functions Called
image.addEventListener("mouseover", swapToNewImage);
image.addEventListener("mouseout", swapImageBack);
}
}
//MOUSE EVENT FUNCTIONS
var swapToNewImage = function(img) {
var secondImage = img.getAttribute("id", "src");
img.src = secondImage;
}
var swapImageBack = function(img) {
var previousImage = img.getAttribute("src");
img.src = previousImage;
}
Let me know if you can help me figure out how to call the image's src attribute so it can be reverted back. Again, I cannot reference specific image names, because that would be a lot easier (: Thank you!
Well, You can use a data attribute to store your src, and a data attribute to store the image you want to swap when mouseover.
Please try the following example.
var swapToNewImage = function(img) {
var secondImage = img.dataset.swapSrc
img.src = secondImage;
}
var swapImageBack = function(img) {
var previousImage = img.dataset.src
img.src = previousImage;
}
<img src="https://images.pexels.com/photos/259803/pexels-photo-259803.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" alt="" data-src="https://images.pexels.com/photos/259803/pexels-photo-259803.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" data-swap-src="https://images.pexels.com/photos/416160/pexels-photo-416160.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" onmouseover="swapToNewImage(this)" onmouseout="swapImageBack(this)">
I also notice that the image tag is generated by code, in order to set the dataset values, we can do this:
var image = new Image();
image.scr = [src]
image.dataset.src = [src]
image.dataset.swapSrc = [swap src]

object HTMLImageElement showing instead of image

I created an array of 2 images and tried to display them, but instead of the images I got the text:
object HTMLImageElement
I am sure my images are in the right directory which I am currently working with.
< template is="auto-binding">
<section flex horizontal wrap layout>
<template repeat="{{item in items}}">
<my-panel>{{item}}</my-panel>
</template>
</section>
<script>
(function() {
addEventListener('polymer-ready', function() {
var createImage = function(src, title) {
var img = new Image();
img.src = src;
img.alt = title;
img.title = title;
return img;
};
var items = [];
items.push(createImage("images/photos/1.jpeg", "title1"));
items.push(createImage("images/photos/2.jpeg", "title2"));
CoreStyle.g.items = items;
addEventListener('template-bound', function(e) {
e.target.g = CoreStyle.g;
e.target.items = items;
});
});
})();
</script>
What am I missing here?
Use:
items.push(createImage(...).outerHTML);
Edit: Changes to original question has rendered the rest of the answer obsolete. But I am leaving it anyway in the hope that OP or someone may learn something.
I got the text: object HTMLImageElement
I am pretty sure you are using something like this to add the new element to DOM:
document.getElementById('#insert_image_here').innerHTML = items[0];
(Edit: What happens here is this: your newly created object items[0] is an HTMLImageElement. When you try to assign it to innerHTML, since innerHTML is type of String, JavaScript will try to call the objects toString() method and set the returned value to innerHTML. For DOM elements toString always returns object XElement.)
What you need to do is this:
document.getElementById('#insert_image_here').appendChild(items[0]);
The easiest and safest way to do this is to put the img in the template and bind the src and title attributes like this:
<template repeat="{{item in items}}">
<my-panel><img src="{{item.src}}" alt="{{item.title}}" title="{{item.title}}"></my-panel>
</template>
Then createImage looks like this
var createImage = function(src, title) {
return {src: src, title: title};
}
Replace
var createImage = function(src, title) {
var img = new Image();
img.src = src;
img.alt = title;
img.title = title;
return img;
};
With
var createImage = function(src,title) {
title = title.replace(/"/g,""");
return '<img src="'+src+'" title="'+title+'" alt="'+title+'" />';
}
It looks like whatever framework thingy you're using is expecting strings, not Image objects ;)

JavaScript method that preloads image before displaying it doesn't work

Within an object constructor there's a method named addToViewport(), which has the role of simply displaying an image after preloading it:
window.onload = function(){
function ViewportObject(){
this.src = "https://chart.googleapis.com/chart?cht=qr&chs=500x500&chl=asdasdasd&choe=UTF-8&chld=L|0";
this.addToViewport = function(){
// Determine the DOM object type to create
var DOM_elem = "img",
obj = $(document.createElement(DOM_elem)),
img = new Object();
obj.addClass("object");
obj.css({"z-index":"100","width":"300px","height":"auto"});
// Preload the image before rendering it and computing its size
img.src = this.src;
img.onload = function(){
obj.attr("src",this.src);
obj.appendTo("body");
}
}
}
var o = new ViewportObject();
o.addToViewport();
}
The problem I've come across is that the script doesn't enter the "onload" event handler block, so the image doesn't get displayed.
I put together a web page with the same script as above on http://picselbocs.com/test/ for you to check out live.
What is it that I'm doing wrong here?
Try this:
change this
img = new Object();
....
img.src = this.src;
img.onload = function(){
obj.attr("src",this.src);
obj.appendTo("body");
}
to
img = new Image();
....
img.onload = function(){
obj.attr("src",this.src);
obj.appendTo("body");
}
img.src = this.src;

Assign Javascript image object directly to page

Is it possible to assign a Javascript image object directly to the DOM? Every example I've seen has the image object being loaded and then the same file name assigned to an HTML element and my understanding is that the actual image data is coming from the browser cache in the filing system.
I want to guarantee that the image is loaded so I want to load it into a Javascript image object have the data in memory and then add it directly to the page.
Is this possible?
Cheers, Ian.
You can create the image element and append it directly to the DOM once it has loaded:
var image = new Image();
image.onload = function(){
document.body.appendChild(image);
};
image.src = 'http://www.google.com/logos/2011/guitar11-hp-sprite.png';
example: http://jsfiddle.net/H2k5W/3/
See:
<html>
<head>
<script language = "JavaScript">
function preloader()
{
heavyImage = new Image();
heavyImage.src = "heavyimagefile.jpg";
}
</script>
</head>
<body onLoad="javascript:preloader()">
<a href="#" onMouseOver="javascript:document.img01.src='heavyimagefile.jpg'">
<img name="img01" src="justanotherfile.jpg"></a>
</body>
</html>
Reference:
http://www.techrepublic.com/article/preloading-and-the-javascript-image-object/5214317
if (document.images) {
var preload_image_object = new Image();
var image_urls = new Array();
image_urls[0] = "http://mydomain.com/image0.gif";
image_urls[1] = "http://mydomain.com/image1.gif";
image_urls[2] = "http://mydomain.com/image2.gif";
image_urls[3] = "http://mydomain.com/image3.gif";
var i = 0;
for(image_url in image_urls) {
preload_image_object.src = image_url;
}
}

Problem with image() object

Look at this script please
var src="some.jpg";
var img = new Image();
img.src = src;
img.id = "crop_image";
$("#crop_image").load(function()
{
$("#crop_cont").append(img);
})
why in my .load function i can't access to img element?
Thanks much
UPDATE:
But the following works
$('<img src="'+src+'" />').load(function()
{
var img = new Image();
img.src = src;
$("#crop_cont").append(img);
})
Neither of those two examples really make any sense.
In the first, you create an Image but you don't add it to the DOM. Thus, when you ask jQuery to go find it, it can't because it's not there yet.
In the second, you create a new image tag, which (internally) is going to give jQuery an actual DOM element to work with. However, that call to append your Image object to the DOM seems superfluous. You've already got an <img> so there's no need for another one.
I'd change the second one as follows:
$('<img src="'+src+'" />').load(function() {
$("#crop_cont").append(this);
});
$("#crop_image") will not find your new image because you haven't added it to the DOM yet. Use $(img) instead.
A correct way to do it would be:
var src="some.jpg";
var img = new Image();
img.src = src;
img.id = "crop_image";
$(img).load(function(){
$("#crop_cont").append(this);
});
#crop_image, does it actually get appended to the doc? if so when?
you need to provide html to that.right
<img src="" />
Otherwise how can it display
image has it's own onload event, it's probably easiest to do something like this
var src="some.jpg";
var img = new Image();
img.id = "crop_image";
img.onload = $("#crop_cont").append(img); // event added
img.src = src;
edit: err, I mean the Image Object.

Categories

Resources