JavaScript - Clicking on an image - javascript

I am programming a browser game in JavaScript and need to create a Card Class.
This class has (with other variables) an image, which should be displayed when I create an object. How do I display the object's image and call a function when the image is clicked?
With this code I can display the image wherever I want, but the OnClick function is called instantly when I open the .htm file instead of when I click in the image.
<html>
<head> </head>
<body>
<script type="text/javascript">
function Card(photo){ // this is my object
this.randomVariable=42;
this.pic = new Image(); // creating an Image object inside my Card class.
this.pic.src=photo;
this.pic.height = 300;
this.pic.width = 200;
this.pic.style.position="absolute"; // this 3 lines should set the image's position, and it does.
this.pic.style.top = 50 + "px";
this.pic.style.left = 50 + "px";
this.OnClick = document.write("lala");
}
var myObject = new Card("cardback.jpg");
myObject = document.body.appendChild(coso1.pic); // is this how I should create the image? It appears where I want, but it doesn't seem a "clean" programming.
myObject.OnClick = document.write("lala" + coso1.pic.offsetLeft + coso1.pic.offsetTop); // this is casted when I open the file, and not when I click on the image. *sadface*
</script>
</body>
</html>
Please, some help with detecting when I click on the image and displaying the image in a less dirty way (if it's possible)?
Thanks in advance!

http://jsfiddle.net/CTWWk/1/
var image = new Image();
image.src = 'https://www.google.co.il/images/srpr/logo4w.png';
image.onclick = function(){
alert('I Clicked an image now !');
};
var divy = document.getElementById('divy');
divy.appendChild(image);

Made some changes to your code. Hope it helps!
<html>
<head> </head>
<body>
<script type="text/javascript">
function Card(photo){
var cardInstance = new Image();
cardInstance.src = photo;
cardInstance.addEventListener('click', function (e) {
alert(1);
});
return cardInstance;
}
var myObject = new Card("cardback.jpg");
document.body.appendChild(myObject);
</script>
</body>
</html>

Related

Getting the width and height of a div or image after it finished loading

I'm creating an image gallery and I need to know the size of the div containing the image or the image itself after it loads. How can I get that? I've tried everything but it gives me the size of the DIV before it loads, which is 1px X 1px.
Basically everything is hidden, you click a link and the image displays, so the div goes from 1px by 1px to for example, say 419px by 1000px. How do I get that final size after the DIV or Image loads? the size can change depending on the device used and the image loaded. Is there anyway to get this information using just JavaScript?
Here's the function. If possible I would like to get the height of the image or the DIV after the image loads in the same function.
here's the function that i am testing
function ShowArt(nam,imgs,)
{
var currentPosition = parseInt(movingDivObj.style.top);
var scrollPos = window.scrollY || window.scrollTop || document.getElementsByTagName("html")[0].scrollTop;
movingDivObj.style.top = currentPosition + scrollPos + "px";
movingDivObj.style.display = "block";
document.getElementById("close").style.display = "block";
document.getElementById("selectedart").style.display = "block";
document.getElementById("artname").style.display = "block";
document.getElementById("background").style.display = "block";
display.src = imgs;
document.getElementById("artname").textContent= nam;
scrollPosition = window.pageYOffset;
document.body.style.position = "fixed";
document.body.style.top = `-${scrollPosition}px`;
}
Thanks!
Try using this DOM event listener, in the callback function you can write the necessary code to get your value I presume:here
In the same way that the "load" event works for the body, it works for images. So you could attach an "load" event on the image and when it triggers, measure the width/height.
const img = document.querySelector('#img')
img.addEventListener('load', (event) => {
console.log('width', event.target.width)
console.log('height', event.target.height)
})
img.src = 'https://via.placeholder.com/900x1000'
Have you tried:
<script>
var myImg = document.getElementById('image');
var realWidth = myImg.naturalWidth;
var realHeight = myImg.naturalHeight;
console.log(realWidth);
</script>
Solution 1:
Use this Solution in your JS file
JavaScript:
window.onload = () => {};//enter the code that gets the image or divs width and height in the {} brackets`
The window.onload function waits till the DOM is loaded and then executes a function. It is used mostly when you need to get default values from a predefined and static element.
Further Readings: https://www.w3schools.com/jsref/event_onload.asp
Solution 2:
NOTE: Use this only if you are using a 'script' tag to use the JS code in your HTML.
Use the script tag at the end of your HTML document
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<!--Your code goes here-->
<script src="myScript.js"></script>
</body>
</html>
Thanks guys I appreciate all the help. I finally found an answer that worked though I got some great ideas. The answer was to have the images preload and when I did that it gave me the height of the image I needed for the next steps. Again thanks very much! I appreciate it. The code I used for this is below. After the images are preloaded I am able to get the width / height of the images so they work in the gallery as planned. It worked like a charm.
var images = new Array()
function preload() {
for (i = 0; i < preload.arguments.length; i++) {
images[i] = new Image()
images[i].src = preload.arguments[i]
}
}
preload(
"Photos/AloneInTheStorm.jpg",
"Photos/deepinthought.jpg",
"Photos/68degrees.jpg",
"Photos/forgotten.jpg",
"Photos/babylycan2.jpg",
"Photos/americancoot.jpg"
)

javaScript: window.open not displaying background image

Please help me, I have been working on this for hours. I have just started playing with JavaScript.
So I have a button that loads a new browser window, loads background image. As below, no problems.
HTML
<script>
setBackground();
</script>
JavaScript
function setBackground() {
document.body.style.backgroundColor = "#000000";
document.body.style.backgroundImage = "url(bg.jpg)"
}
Then I try to load another window on button click but the background image will not work. The window works, I can change the background color no problem, but I can't get the image to load. code below.
//load screen on button click
document.getElementById("startButton").onclick = function() {
load()
};
function load() {
//create the new screen
newWindow = window.open("", "", "width=1550, height=800");
newWindow.id = "game";
newWindow.document.body.style.backgroundColor = "#000000";
newWindow.document.body.style.backgroundImage = "url(bg.jpg)";
}
The files and images are located in the same folder, I'm using the same image, it works in the first example but not the second.
Please help!!! Thanks in advance.
Check this link and click on Run
https://www.w3schools.com/code/tryit.asp?filename=GM9IO9Q6SDNL
try this.
<!DOCTYPE html>
<html>
<body onload="setBackground()" >
</body>
<script>
function setBackground() {
document.body.style.backgroundImage = "url(https://www.w3schools.com/html/pic_trulli.jpg)"
newWindowSetBackgroundload()
}
function newWindowSetBackgroundload() {
//create the new screen
var newWindow = window.open("", "", "width=1550, height=800");
//Id use for Uniq thats why its render only one time
// newWindow.id = "game";
//use class for multiple windows genration
newWindow.class = "game";
newWindow.document.body.style.backgroundColor = "#000000";
newWindow.document.body.style.backgroundImage = "url(https://www.w3schools.com/html/pic_trulli.jpg)";
}
</script>
</html>

Add dynamically a gif image with animation

I'm trying to load programmatically an img with a .gif extension. But the animation only happens once.
How can I add more img and see the animation every time I add a new img, not just the final state?
Note: I do not want a loop gif. I just want the next img to behave just like the first, animate then stop.
var topval = 10;
var right = 10;
var addStar = function() {
var img = $('<img id="'+topval+'">');
img.attr('src','https://s3-sa-east-1.amazonaws.com/musicamise/astronautAnimatedGif.gif');
img.attr('alt','alt'+topval);
img.css('position','absolute');
img.css('right', right+'px');
img.css('top', topval+'px');
img.appendTo('body');
topval = topval+10;
right = right+10;
};
$("#addStar").click(addStar);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body style="margin:0;padding:0;">
<button id="addStar">Click do add</button>
</body>
Thanks in advance.
You can hack around this problem by appending a random query string parameter to the URL. This tricks the browser into thinking the image is different each time. For example:
https://s3-sa-east-1.amazonaws.com/musicamise/astronautAnimatedGif.gif?x=' + Math.random()
var topval = 10;
var right = 10;
var addStar = function(){
var img = $('<img id="'+topval+'">');
img.attr('src','https://s3-sa-east-1.amazonaws.com/musicamise/astronautAnimatedGif.gif?x=' + Math.random());
img.attr('alt','alt'+topval);
img.css('position','absolute');
img.css('right', right+'px');
img.css('top', topval+'px');
img.appendTo('body');
topval = topval+10;
right = right+10;
}
$("#addStar").click(addStar);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body style="margin:0;padding:0;">
<button id="addStar">Click do add</button>
</body>
Thanks in advance.
Your problem is because the browser takes the same cache image. When you change the URL of the image, it's like you're looking for another image. The downside of this is that he always makes a new request for the image.
var topval = 10;
var right = 10;
var count = 0;
var addStar = function(){
var img = $('<img id="'+topval+'">');
img.attr('src','https://s3-sa-east-1.amazonaws.com/musicamise/astronautAnimatedGif.gif?count='+count++ );
img.attr('alt','alt'+topval);
img.css('position','absolute');
img.css('right', right+'px');
img.css('top', topval+'px');
img.appendTo('body');
topval = topval+10;
right = right+10;
}
$("#addStar").click(addStar);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body style="margin:0;padding:0;">
<button id="addStar">Click do add</button>
</body>
create a div
set your gif as a background image of your div:
$('myDiv').css('background-image', 'url(' + imageUrl + ')');

Easel.js: Browser compatibility when placing an image within a container and adding mouse interactions

I'm going to start this question off by saying that this is 100% working in Firefox (v21.0). For some reason it's not working in Google Chrome (v27.0.1453.94m). It also doesn't work in IE10.
Here is the JavaScript code I'm having issues with:
function canvasDrawBackground(value){
console.log(value);
stage.removeChild(background);
var temp = new createjs.Bitmap("images/bg_" + value +".jpg");
background = new createjs.Container();
background.x = background.y = 0;
background.addChild(temp);
stage.addChild(background);
background.addEventListener("mousedown", function(evt) {
var offset = {x:evt.target.x-evt.stageX, y:evt.target.y-evt.stageY};
evt.addEventListener("mousemove",function(ev) {
ev.target.x = ev.stageX+offset.x;
ev.target.y = ev.stageY+offset.y;
stage.update();
});
});
stage.update();
}
So, in Firefox the above code works, as in the image is added to the canvas and you can drag it around.
In Chrome / IE10 nothing happens - or more simply nothing appears on the canvas. I think the issue is in regards to when I add the image into the container, as I can place other items into the container and it works.
I am using http://code.createjs.com/easeljs-0.6.1.min.js and this code is based off of the "drag" tutorial. Here's the code from the tutorial:
<!DOCTYPE html>
<html>
<head>
<title>EaselJS demo: Dragging</title>
<link href="../../shared/demo.css" rel="stylesheet" type="text/css">
<script src="http://code.createjs.com/easeljs-0.6.0.min.js"></script>
<script>
var stage, output;
function init() {
stage = new createjs.Stage("demoCanvas");
// this lets our drag continue to track the mouse even when it leaves the canvas:
// play with commenting this out to see the difference.
stage.mouseMoveOutside = true;
var circle = new createjs.Shape();
circle.graphics.beginFill("red").drawCircle(0, 0, 50);
var label = new createjs.Text("drag me", "bold 14px Arial", "#FFFFFF");
label.textAlign = "center";
label.y = -7;
var dragger = new createjs.Container();
dragger.x = dragger.y = 100;
dragger.addChild(circle, label);
stage.addChild(dragger);
dragger.addEventListener("mousedown", function(evt) {
var offset = {x:evt.target.x-evt.stageX, y:evt.target.y-evt.stageY};
// add a handler to the event object's onMouseMove callback
// this will be active until the user releases the mouse button:
evt.addEventListener("mousemove",function(ev) {
ev.target.x = ev.stageX+offset.x;
ev.target.y = ev.stageY+offset.y;
stage.update();
});
});
stage.update();
}
</script>
</head>
<body onLoad="init();">
<canvas id="demoCanvas" width="500" height="200">
alternate content
</canvas>
</body>
</html>
To simulate my issue, change "var circle = new createjs.Shape();" into a bitmap / image, createjs.Bitmap("images/bg_" + value +".jpg");. It then doesn't render.
Any help is greatly appreciated! Hopefully I'm just doing it wrong. :P
This is probably because the image is not loaded. If you only update the stage after creating it, the image may not display. I would recommend adding a callback to the image to update the stage after its loaded.
// Simple approach. May not work depending on the scope of the stage.
var temp = new createjs.Bitmap("images/bg_" + value +".jpg");
temp.image.onload = function() { stage.update(); }
It also may make sense to preload the images you intend to use.

2 or more async requests in javascript to load image or do anything else

Single request and response model at one time do not utilizes full network/internet bandwidth, thus resulting in low performance. (benchmark is of half speed utilization)
how to make this code use 2 or 3 or more async requests instead of one.(ajax)
or do i need multi threading? and is it possible in javascript?
(this is for making a video out of an ip )
every time the image changes on request. and yes i need to be async with multiple fetch requests (not single as i explained above) or you recomend threads?
<html>
<head> <script language="JavaScript">
// Global vars
img = 'http://pastebin.com/i/t.gif';
timeout = 1000;
next = 0;
function onLoad( ) {
setTimeout( 'reloadImage( )', timeout );
}
// Reloader
function reloadImage( ) {
next = ( new Date( ) ).getTime( ) + timeout;
document.images.dv.src = img + "?" + next;
}
</script>
</head>
<body>
<img src="img" name="dv" onLoad="onLoad( )">
</body>
</html>
and
<html>
<head>
</head>
<body>
<div id="container"></div>
<script language="JavaScript">
var canLoad = true;
var container = document.getElementById("container");
var image = document.createElement("img");
image.onload = function() {
canLoad = true;
console.log("Image reloaded.");
}
var imageUrl = "http://url/snapshot.jpg";
var fps = 2;
container.appendChild(image);
function loadImage() {
if (canLoad) {
canLoad = false;
var str = new Date().getTime();
image.setAttribute("src", imageUrl + "?" + str);
console.log("Reloaded now.");
} else {
console.log("Can't reload now.");
}
}
setInterval(loadImage, fps); // 30 fps
</script>
</body>
</html>
Not actually tested, and I think it'll very likely to cause a "stack overflow" eventually (if you directly implement it), but you may still give it a look:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
(function(){
var img="/*url*/";
var interval=50;
var pointer=0;
function showImg(image,idx)
{
if(idx<=pointer) return;
document.body.replaceChild(image,document.getElementsByTagName("img")[0]);
pointer=idx;
preload();
}
function preload()
{
var cache=null,idx=0;;
for(var i=0;i<5;i++)
{
idx=Date.now()+interval*(i+1);
cache=new Image();
cache.onload=(function(ele,idx){return function(){showImg(ele,idx);};})(cache,idx);
cache.src=img+"?"+idx;
}
}
window.onload=function(){
document.getElementsByTagName("img")[0].onload=preload;
document.getElementsByTagName("img")[0].src="/*initial url*/";
};
})();
</script>
</head>
<body>
<img />
</body>
</html>
What it does:
When the initial image loads, preload() is called;
When preload() is called, it creates 5 image cache, and each attach its onload event to showImg();
When showImg() is called, it checks whether the current index is behind current pointer, and if it does, replace the current image with this new one, and call preload();
Back to 2.
If you really going to implement this, increase interval and decrease i<5. Also, a caching/queuing mechanic to check how many images in cache/queue before loading the next queue would be nice.
Also, notice that I didn't use getElementById to get the image, because there will be no stable ID.

Categories

Resources