I have this id in my html code:
<div id="me">
<img src="Me.JPG" alt="Me" width="450" height="450" alt="picture" align="right"/>
</div>
how can i change the picture every 3 seconds once the mouse is over the picture,
and to go back to the original picture once the mouse is out?
You can create a function that will change the image every 3 seconds. Then, when you mouse over the image, call the function and start a timer. When the mouse leaves the image, clear the timer.
var img = document.getElementById( "me" ).getElementsByTagName( "img" )[0];
var images = ["Me.JPG", "new image path", "..."];
var i = 1;
var timer;
function change() {
img.src = images[i];
if ( ++i >= images.length ) {
i = 0;
}
timer = setTimeout( change, 3000 );
}
img.onmouseover = function() {
timer = setTimeout( change, 3000 );
};
img.onmouseout = function() {
img.src = images[0];
clearTimeout( timer );
};
Here's a link to a quick solution on JsFiddle: http://jsfiddle.net/jJBEu/2/
var img = document.getElementById('me').getElementsByTagName('img')[0],
index = 0,
sources = [
'http://icons.iconarchive.com/icons/iconka/social-treat/128/yumtube-icon.png',
'http://icons.iconarchive.com/icons/iconka/social-treat/128/sweeter-icon.png',
'http://icons.iconarchive.com/icons/iconka/social-treat/128/facebow-icon.png'
],
timer;
img.addEventListener('mouseover', swapImages, false);
img.addEventListener('mouseout', function(){
clearTimeout(timer);
img.src = sources[0];
}, false);
function swapImages(event, setindex){
index = index == (sources.length - 1) ? 0 : index + 1;
timer = setTimeout(function(){
img.src = sources[index];
swapImages();
}, 3000);
}
Edited to fix a dumb mistake where I was checking array index against length without subtracting 1.
html:
<img src="Me.JPG" alt="Me" width="450" height="450" alt="picture" align="right"
onmouseover="animate(this)" onmouseout="stopanimation()" />
javascript:
/* globals */
var animTimer = null;
var animImg = null;
var images = [new Image(), new Image(), new Image(), new Image(), new Image(),new Image()];
var imgIndex = 0;
/* pre-load images in browser cash */
images[0].src = "Me.JPG";
images[1].src = "anim1.gif";
images[2].src = "anim2.gif";
images[3].src = "anim3.gif";
images[4].src = "anim4.gif";
images[5].src = "anim5.gif";
/* animation */
function animate(img){
if (typeof img != 'undefined'){animImg = img;}
imgIndex += 1;
if (imgIndex>images.length-1){imgIndex=1;}
animImg.src=images[imgIndex].src;
animTimer = setTimeout(animate, 3000);
}
function stopanimation(){
clearInterval(animTimer);
animImg.src = images[0].src;
}
Something like, just give the img an id of myImg (or whatever you want):
var img_arr = ["img1.png", "img2.png", "img3.png"],
img_index = 0,
interval_id = 0,
div = document.getElementById("me"),
img = document.getElementById("myImg");
div.onmouseover = function () {
interval_id = window.setInterval(function () {
if (img_index === (img_arr.length - 1)) {
img_index = 0;
}
img.src = img_arr[img_index++];
}, 3000);
};
div.onmouseout = function () {
window.clearInterval(interval_id);
};
Related
I have been trying to draw a tile-like map to the canvas, although if i try to draw the same sprite twice, it will only render the final call of drawImage. Here is my code if it helps :
window.onload = function(){
function get(id){
return document.getElementById(id);
}
var canvas = get("canvas");
ctx = canvas.getContext("2d");
canvas.width = 160;
canvas.height = 160;
grass = new Image();
water = new Image();
grass.src = "res/Grass.png";
water.src = "res/Water.png";
path = {
draw: function(image,X,Y){
X = (X*32)-32;
Y = (Y*32)-32;
image.onload = function(){
ctx.drawImage(image,X,Y);
}
},
}
path.draw(water,2,2);
path.draw(grass,1,2);
path.draw(grass,1,1);
path.draw(water,2,1);
}
You're overwriting onload on the image next time you call it.
Think of it this way:
var image = {
onload: null
};
// Wait for the image to "load"
// Remember, onload is asynchronous so it won't be called until the rest of
// your code is done and the image is loaded
setTimeout(function() {
image.onload();
}, 500);
image.onload = function() {
console.log('I will never be called');
};
image.onload = function() {
console.log('I overwrite the previous one');
};
Instead, you might try waiting for your images to load then do the rest of your logic.
var numOfImagesLoading = 0;
var firstImage = new Image();
var secondImage = new Image();
// This is called when an image finishes loading
function onLoad() {
numOfImagesLoading -= 1;
if (numOfImagesLoading === 0) {
doStuff();
}
}
function doStuff() {
// This is where you can use your images
document.body.appendChild(firstImage);
document.body.appendChild(secondImage);
}
firstImage.src = 'http://placehold.it/100x100';
firstImage.onload = onLoad;
numOfImagesLoading += 1;
secondImage.src = 'http://placehold.it/200x200';
secondImage.onload = onLoad;
numOfImagesLoading += 1;
I am trying to make really simple image loader for my game but I can't find out why this isn't working.. Here is my code:
window.onload = function() {
var canvas = document.getElementById('gameCanvas');
var ctx = canvas.getContext('2d');
var images = [];
function loadImages(imageFiles) {
var loadedImages = [];
for(var i = 0; i < imageFiles.length; i++) {
var image = new Image();
image.onload = function() {
alert("Loaded");
}
image.src = imageFiles[i];
loadedImages[i] = image;
}
return loadedImages;
}
function init() {
images = loadImages(['img/1.png', 'img/2.png']);
main();
}
function main() {
ctx.drawImage(images[1], 0,0);
}
init();
}
All I see is blank canvas without an image.
Use Promise, The Promise object is used for deferred and asynchronous computations. A Promise represents an operation that hasn't completed yet, but is expected in the future.
Promise.all(), The Promise.all(iterable) method returns a promise that resolves when all of the promises in the iterable argument have resolved.
function loadImages(imageFiles) {
var promiseArr = [];
for (var i = 0; i < imageFiles.length; i++) {
var eachPromise = new Promise(function(resolve, reject) {
var image = new Image();
image.onload = function() {
alert('Loaded!');
resolve();
}
image.src = imageFiles[i];
});
promiseArr.push(eachPromise);
}
return promiseArr;
}
function init() {
var AllImages = ['https://www.google.co.in/logos/doodles/2016/earth-day-2016-5741289212477440.2-5643440998055936-ror.jpg', 'https://www.google.co.in/logos/doodles/2016/earth-day-2016-5741289212477440.3-5700735861784576-ror.jpg'];
var allPromises = loadImages(AllImages);
Promise.all(allPromises).then(function() {
alert('All Loaded');
main();
});
}
function main() {}
init();
try replacing
image.onload = function() {
alert("Loaded");
}
with
if(i==1){
image.onload = function() {
main();
}}
when the second image is loaded, your function is called
then edit the code to suit your needs
I will edit more in a while
Images are loaded asynchronously so when you try to read the file in main, the image still is loading. So you need to wait until all the images are loaded.
window.addEventistener("load", function() {
var canvas = document.getElementById('gameCanvas');
var ctx = canvas.getContext('2d');
var images = [];
function loadImages(imageFiles, completeFnc) {
var loadedImages = [],
loadedCnt = 0;
for(var i = 0; i < imageFiles.length; i++) {
var image = new Image();
image.onload = function() {
loadedCnt++; //increment the count
if(loadedCnt==imageFiles.length) { //if count equals total, fire off callback
completeFnc();
}
};
image.onerror = function () {
alert("There was a problem loading the images");
};
image.src = imageFiles[i];
loadedImages[i] = image;
}
return loadedImages;
}
function init() {
images = loadImages(['img/1.png', 'img/2.png'], main);
}
function main() {
ctx.drawImage(images[1], 0,0);
}
init();
});
This should work better
var images = ['img/1.png', 'img/2.png'], loadedImages = [], canvas,ctx, idx=0:
function main() {
ctx.drawImage(images[1], 0, 0);
}
function loadImages() {
if (loadedImages.length == images.length) {
main();
return;
}
var image = new Image();
image.onload = function() {
loadedImages.push(this);
loadImages();
idx++;
}
image.src = imageFiles[idx];
}
function init() {
canvas = document.getElementById('gameCanvas');
ctx = canvas.getContext('2d');
loadImages();
}
window.onload = function() {
init();
}
You need to push items into an array. Replace
loadedImages[i] = image;
with
loadedImages.push(image);
I have the following code where I am loading only one image. But I want to load multiple images from e folder and then to fade them in and out. But what I am interesting in, is how can I load all images from a folder without to repeat the code, as src="frames/frame_1" src="frames/frame_2" i want something soft as src="frames/frame_" + i + ".jpg" where i is the number of the frame
this is how I load only one image now
var img = new Image();
var div = document.getElementById('foo');
img.onload = function() {
div.appendChild(img);
};
img.src = 'frames/frame_1.jpg';
It's relatively simple. You basically put the code you already had in a loop:
var img, i,
imageCount = 5,
div = document.getElementById('foo');
for(i = 0; i < imageCount; i++){
img = new Image();
img.onload = function() {
div.appendChild(img);
};
img.src = 'frames/frame_' + i + '.jpg';
}
You can use a loop for :
var img,
div = document.getElementById('foo');
for (var i = 0, nbImg = 5; i < nbImg; i++) {
img = new Image();
img.onload = function() {
div.appendChild(img);
};
img.src = 'frames/frame_'+i+'.jpg';
}
UPDATED
I have an HTML code below:
<canvas id="canvas1"></canvas>
<canvas id="canvas2"></canvas>
I have a function below:
var Context;
function onSign(canvas){
var ctx = document.getElementById(canvas).getContext('2d');
SigWebSetDisplayTarget(ctx);
tmr = setInterval(SigWebRefresh, 50);
}
function SigWebSetDisplayTarget( obj ){
Context = obj;
}
I called the function OnSign twice with different canvas id parameters.
OnSign('canvas1');
OnSign('canvas2');
Below is the SigWebRefresh function that is repeatedly called for a reason.
function SigWebRefresh(){
xhr2 = new XMLHttpRequest();
requests.push(xhr2);
xhr2.open("GET", baseUri + "SigImage/0", true );
xhr2.responseType = "blob"
xhr2.onload = function (){
var img = new Image();
img.src = 'image.jpg';
img.onload = function (){
Ctx.drawImage(img, 0, 0);
revokeBlobURL( img.src );
img = null;
}
}
xhr2.send(null);
}
After that, I noticed that the two canvas was being updated and the image is loaded to the 2 canvas. Why is it? I have to load the image, only to the last canvas I supplied with the function OnSign. Where am I missing?
var Context; is declared in global scope
OnSign('canvas1');
OnSign('canvas2');
Doing so you are assigning value of canvas number two.
Update: http://jsfiddle.net/bmynvtLd/2/
This is what you desired to update both contexts? if yes this is how you pass the parameter to setInterval function: setInterval(function() {SigWebRefresh(ctx)}, 300);
running example:
var images = ['http://img09.deviantart.net/6d02/i/2015/284/0/b/beginning_autumn_by_weissglut-d9cssxw.jpg', 'http://orig06.deviantart.net/063c/f/2013/105/3/6/free_crystal_icons_by_aha_soft_icons-d61tfi1.png', 'http://img15.deviantart.net/b126/i/2015/118/c/1/this_small_tree_by_weissglut-d8re8q7.jpg', 'http://img00.deviantart.net/84f8/i/2015/284/d/f/nuclear_light_by_noro8-d9cs4u6.jpg'];
function OnSign(canvas){
var ctx = document.getElementById(canvas).getContext('2d');
tmr = setInterval(function() {SigWebRefresh(ctx)}, 300);
}
OnSign('canvas1');
OnSign('canvas2');
var index = 0;
function MyIndex()
{
// console.log(index);
index = images.length == index ? 0 : index+1;
return images[index];
}
function SigWebRefresh(Context){
var img = new Image();
img.src = MyIndex();
img.onload = function (){
Context.drawImage(img, 0, 0);
img = null;
}
}
Before your read this, my first account was blocked because i asked bad questions.. So please dont vote negative but say what i am doing wrong
Sooo I have this script:
var img1 = new Image()
img1.src="image1.jpg"
var img2 = new Image()
img2.src="image2.jpg"
var img3 = new Image()
img3.src="image3.jpg"
function Canvas() {
var ctx = document.getElementById('slider').getContext('2d');
var pic=1
function slider() {
this.draw = function() {
if(pic<4){pic++}
else{
pic=1
}
var img = "img"+pic
ctx.drawImage(img,0,0,ctx.canvas.width,ctx.canvas.height)
}
}
var slider = new slider();
function draw() {
ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height);
ctx.save();
//draw
slider.draw();
//draw
ctx.restore();
}
var animateInterval = setInterval(draw,100)
}
window.addEventListener('load', function(event) {
Canvas();
});
I am trying to draw the image 1 or 2 or 3 on my canvas. But I also have the var pic wich has the number. So i tried ctx.drawimage(img+pic,0,0) or var img = "img"+pic and draw it then. But it doesnt work for me.
I hope you accept my question and can answer it, THNX
Use an array instead
var img = [];
/* you should use a for loop here */
for (var i = 0; i < 3; i++) {
img[i] = new Image();
img[i].src = "image" + (i+1) ".jpg";
}
and later you refer the right image with img[pic]. Be only sure to use an index between 0 and img.length - 1
Don't use separate variables, use an array.
var images = [ new Image(), new Image(), new Image() ];
for (var i = 0; i < images.length; i++) {
images[i].src = "image" + (i+1) + ".jpg";
}
Then refer to the array in the Slider() function:
var pic = 0;
function slider() {
this.draw = function() {
pic = (pic + 1) % images.length;
var img = images[pic];
ctx.drawImage(img,0,0,ctx.canvas.width,ctx.canvas.height)
}
}
The error seems to be that you refer to the string "img1" and not the object img1. Try use an array instead.
Set the following:
...
var pic=0;
var img=[img1,img2,img3];
function slider() {
this.draw = function() {
if(pic<3){pic++}
else{
pic=0;
}
ctx.drawImage(img[pic],0,0,ctx.canvas.width,ctx.canvas.height)
}
}
...