I would like to change the image after refresh the page, but it doesn't work
Here is the javascript part
<script>
var theImages = [
"../images/casblanca.jpg",
"../images/casblanca2.jpg",
"../images/spot.jpg";
];
function changeImage(){
var size=theImages.length;
var x = Math.floor(size*Math.random())
document.getElementById("spotlight").src = theImages[x];
}
</script>
Here is the html main part
<nav class="spot" onload="changeImage()">
<h1>SPOTLIGHT</h1>
<img id="spotlight" width="1000" height="600" alt="">
</nav>
1) You are using and extra semi colon (;)
"../images/spot.jpg";
at the end of your last image. Go ahead and delete it.
2) Use the onload event in the body tag.
Here's a working solution. Hope it helps!
var theImages = [
"http://media.caranddriver.com/images/media/51/25-cars-worth-waiting-for-lp-ford-gt-photo-658253-s-original.jpg",
"https://carfromjapan.com/wp-content/uploads/2016/10/5-Best-Rated-Cars-of-2016.jpg",
"https://i.ytimg.com/vi/TzcS7Mcq2oA/maxresdefault.jpg"
];
function changeImage(){
var size=theImages.length;
var x = Math.floor(size*Math.random())
document.getElementById("spotlight").src = theImages[x];
}
<body onload="changeImage()">
<nav class="spot">
<h1>SPOTLIGHT</h1>
<img id="spotlight" width="1000" height="600" alt="">
</nav>
The onload attribute is not supported on the <nav> element. Try it on the <body>
There is also a syntax error in your image array. An unnecessary semicolon.
See working example below:
var theImages = [
"https://dummyimage.com/1000x600/000/fff&text=Image+1",
"https://dummyimage.com/1000x600/000/f0f&text=Image+2",
"https://dummyimage.com/1000x600/000/ff0&text=Image+3"
];
function changeImage(){
var size=theImages.length;
var x = Math.floor(size*Math.random())
document.getElementById("spotlight").src = theImages[x];
}
<body onload="changeImage()">
<nav class="spot" >
<h1>SPOTLIGHT</h1>
<img id="spotlight" width="1000" height="600" alt="">
</nav>
</body>
Separate CSS, JS and HTML.
Declare the varibles as
var theImages = [],
size, x;
Remove the onload() function.
Rewrite the random function as the following.
x = Math.floor(Math.random() * size);
Math.random() returns a floating-point, pseudo-random number between 0 (inclusive) and 1 (exclusive).
Here Math.floor always return a value among 0,1,2.
Rewrite the code as the following.
size = theImages.length;
x = Math.floor(Math.random() * size);
document.getElementById("spotlight").src = theImages[x];
var theImages = [],
size, x;
theImages = [
"https://www.w3schools.com/w3css/img_car.jpg",
"https://www.w3schools.com/css/paris.jpg",
"https://www.w3schools.com/css/trolltunga.jpg"
];
size = theImages.length;
x = Math.floor(Math.random() * size);
document.getElementById("spotlight").src = theImages[x];
#spotlight {
width: 1000px;
height: 600px;
}
<h1>SPOTLIGHT</h1>
<img id="spotlight" alt="">
Related
I am trying to re-create the classic mobile game "Snake" using HTML/CSS3 and Javascript. When I run what I have in chrome I get the unexpected token error on line 41. Why is the semi-colon unexpected? The code I have so far is below.
$(document).ready(function(){
//define vars
var canvas = $('#canvas')[0];
var ctx = canvas.getContext("2d");
var w = canvas.width();
var h = canvas.height();
var cw = 15;
var d = "right";
var food;
var score;
var speed = 130;
//Snake Array
var snake_array;
//initalizer
function init(){
create_snake();
create_food();
score = 0;
if(typeof game_loop != "undefined") clearInterval(game_loop);
game_loop = setInterval(paint, speed);
}
init();
function create_snake(){
var length = 5;
snake_array =[];
for(var i = length-1;i >=0;i--){
snake_array.push({x: i,y :0});
}
}
//Create Food
function create_food(){
food = {
x:Math.round(Math.random()*(w-cw)/cw),
y:Math.round(Math.random()*(h-cw)/cw); // <-- line 41
};
}
});
HTML CODE
<!DOCTYPE html>
<html>
<head>
<title>Snake Game</title>
<link rel="stylesheet" href="style.css" type="text/css">
</head>
<body>
<div class="container">
<div id ="overlay">
Your final score: <span id = "final_score">
</span>
<br>
<a onclick="window.location.reload()" href="#">Click to play again!</a>
</div>
<canvas id="canvas" width="600" height="400">
</canvas>
<div id="stats">
<div class="score"></div>
<div class="score"></div>
<button onclick="resetScore()" id="reset_score">Reset high score</button>
</div>
</div>
<!-- JQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<!-- Main JS -->
<script src="C:\Users\student\Desktop\SnakeGame\script.js"></script>
</body>
</html>
When defining a variable like this x: (typically used in objects) you cannot put a ; after the last defined variable like you did:
food = {
x:Math.round(Math.random()*(w-cw)/cw),
y:Math.round(Math.random()*(h-cw)/cw); // <-- remove this semi-colon
};
Do this instead
food = {
x:Math.round(Math.random()*(w-cw)/cw),
y:Math.round(Math.random()*(h-cw)/cw)
};
I hope I was to any help :3
I have two images in two different section and div.I want to get the original dimension at same time and send to my java script file to do some calculation. How do I get the images dimension at the same time.
html file
<section id ="hi">
<img src = "images/hi.png" onload = "OnImageLoad(event);" />
</section>
<section id = "bye">
<img src = "images/hi.png" onload = "OnImageLoad(event);"/>
</section>
js
function OnImageLoad(evt) {
var img = evt.currentTarget;
// what's the size of this image
var w = $(img).width();
var h = $(img).height();
In this code I am able to get the images dimension of images,But they return dimension of only one images.I want to get the dimension of both images at same time.
Something like this:
function OnImageLoad(evt) {
var img1 = evt.currentTarget;
var img2 = evt.currentTarget;
// what's the size of this image
var w1 = $(img1).width();
var h1 = $(img1).height();
var w2 = $(img2).width();
var h2 = $(img2).height();
You can not do that, they are async tasks. You can only calculate the size of the image only when they are completely loaded, so If first image is of higher size then the second image, it will take more time to calculate the first image size then the second.
What you can do is, fetch both the image sizes aynchronously, and when both of them are done you can do the calculations.
var sizes = [];
var counter = 0;
function OnImageLoad(evt) {
var img = evt.currentTarget;
// what's the size of this image
var w = $(img).width();
var h = $(img).height();
counter++;
sizes.push({
height: h,
width: w
});
if (counter == 2) {
callAnotherFunction(sizes)
}
}
prepending the variables with a custom value should make it possible.
HTML
<section id ="hi">
<img src = "images/hi.png" onload = "OnImageLoad(event,1);" />
</section>
<section id = "bye">
<img src = "images/hi.png" onload = "OnImageLoad(event,2);"/>
</section>
JS
function OnImageLoad(evt, pre) {
var img = evt.currentTarget;
// what's the size of this image
eval("var w" + pre + " = $(img).width()");
eval("var h" + pre + " = $(img).height()");
Ive not tested this though.
function OnImageLoad() {
var img1 = document.getElementById("Image1");
var img2 = document.getElementById("Image2");
// what's the size of this image
var w1 = img1.width;
var h1 = img1.height;
var w2 = img2.width;
var h2 = img2.height;
}
Html:
<section id ="hi">
<img id="Image1" src = "images/hi.png"/>
</section>
<section id = "bye">
<img id="Image2" src = "images/hi.png"/>
</section>
Call this function on window.onload=OnImageLoad();
function OnImageLoad(evt) {
//This function will be called on each image load and will iterate all the image inside this dom
var images = $('img');
for(var i =0 ;i<images.length; i++) {
// what's the size of this image
var w = $(images[i]).width();
var h = $(images[i]).height();
//For each file you will have width and height of the image
console.log('width of image-'+i+': ',w);
console.log('height of image-'+i+': ',h);
}
}
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.7.2.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<section id ="hi">
<img src = "http://cdn.mysitemyway.com/etc-mysitemyway/icons/legacy-previews/icons-256/3d-glossy-green-orbs-icons-business/103491-3d-glossy-green-orb-icon-business-tool-screwdriver.png" onload = "OnImageLoad(event);" />
</section>
<section id = "bye">
<img src = "http://cdn.mysitemyway.com/etc-mysitemyway/icons/legacy-previews/icons-256/3d-glossy-orange-orbs-icons-business/105429-3d-glossy-orange-orb-icon-business-tool-hammer4-sc44.png" onload = "OnImageLoad(event);"/>
</section>
</body>
</html>
enter link description here
<!-- with thanks to http://stackoverflow.com/questions/25407926/spawn-random-images-
in-canvas-in-javascript-->
<!--http://www.freesfx.co.uk/download/?type=mp3&id=11028
--audio loader--
http://stackoverflow.com/questions/18826147/javascript-audio-play-on-
click-->
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<title>Street</title>
<script type="text/javascript">
var can, ctx;
var sprite = new Array();
var counter = 0;
var rot = 0;
var centerX = -320;
var centerY = -170;
var sprite = new Array(id); // Array to hold the filenames
function init() {
can = document.getElementById("can");
ctx = can.getContext("2d");
// get images into array
sprite[0] = document.getElementById("b1");
sprite[1] = document.getElementById("b2");
sprite[2] = document.getElementById("b3");
sprite[3] = document.getElementById("b4");
// draw lights out
draw();
// wait 3 sec, then begin animation
var t = setTimeout(light, 30);
}
function light() {
var wait = 600;
counter++;
if (counter == 4) {
counter = 0;
wait += (Math.random() * 1500);
rot += .01;
}
draw();
setTimeout(light, wait);
}
function draw() {
ctx.clearRect(0, 0, can.width, can.height);
ctx.save();
ctx.translate(can.width / 2, can.height / 2);
ctx.drawImage(sprite[counter], centerX, centerY);
ctx.restore();
}
function choseRandom(range) {
if (Math.random)
return Math.round(Math.random() * (range-1));
else {
var now = new Date();
return (now.getTime() / 1000) % range;
}
}
var choice = choseRandom(id);
</script>
</head>
<body onload="init()">
<audio id="Mp3Me" autoplay autobuffer controls>
<source src="au1.mp3">
<source src="au1.ogg">
</audio>
<img id="b1" style="display:none" src="1.png" >
<img id="b2" style="display:none" src="2.png" >
<img id="b3" style="display:none" src="3.png" >
<img id="b4" style="display:none" src="4.png" >
<canvas class="canvas" id="can" width="640" height="350" style=" border:1px solid #6F2E0D; ">
</canvas>
<script>
function play(){
var audio = document.getElementById("audio");
audio.play();
}
</script>
<input type="button" value="PLAY" onclick="play()">
<audio id="audio" src="door.mp3" ></audio>
<div id="container"></div>
<script language="JavaScript">
document.writeln('<td' + '><img src="'
+ ranimage[choice] + '" height="180" width="160" border="0" ><' +
'/td>');
</script>
<div id='container'>
<img id = "image2" src='door.png' />
</body>
</html>
The above code works with thanks to stack overflow.
Basically at the moment this code displays images in sequence non randomly, it uses the array to fetch them, and show them. The code then regulates the speed of the image display. There is also a sound player, and a button with a sound.
I managed after some considerable searching to animate a simple sequence of png files. However I have been trying to ad start stop button and a math random function (preferably the music on-click would start everything going).
I want to add a random function to the array,so that it displays images randomly. however the best I could do was, not to brake the code, or to get is to speed up the animation. Can some one please modify my code to add these functions or please point me to some place that would help.
The randomized array would be really useful.
Demo: http://jsfiddle.net/techsin/dtz0yj4y/
Code
function shuffle (arr) {
arr.forEach(function(e,i){
var rand = ~~(Math.random()*(arr.length-1));
arr[i] = arr[rand];
arr[rand] = e;
});
}
var myArr = [1,2,3,4,5];
shuffle(myArr); //myArr is now shuffled!
Example...
(there was a mistake, updated)
For example,
var array = [1,2,3,4,5]
for(i=0; i<array.length;i++){
var dist = Math.floor( Math.random() * array.length )
var swp = array[i]
array[i] = array[dist]
array[dist] = swp
}
console.log(array) //=> shuffled
I have a simple game where image moves randomly and score increases when user clicks on it.
The first image displays before game is started, which when clicked calls the play() function in javascript, which hides that image and displays the image that is to be used for the game.
That is where my code is stuck, it does not call the function play(). I am new to javascript and html. Any help would be great!
Here is my code
<html>
<head>
<title>Image click Game!</title>
<script>
global var score = 0;
global var left=400;
global var top = 100;
function play() {
var game = document.getElementById('game');
var firstDiv = document.getElementById('firstDiv');
var height = window.innerHeight;
var width = window.innerWidth;
firstDiv.style = 'display : none';
game.style='display : block';
setInterval("move()", 1000);
}
function move() {
var randomNumberX = Math.floor(Math.random()*11)-5;
var randomNumberY = Math.floor(Math.random()*11)-5;
left = left + randomNumberX;
top = top+randomNumberY;
var im = document.getElementById('image');
im.style.left = left;
im.style.top = top;
}
</script>
</head>
<body>
<div id ="firstDiv" style="display : block">
<img src="pics/playgame.gif" width="108" height="106" onClick = "play()"/></a>
</div>
<div id="game" style="display : none">
<p>"Score: " + score</p>
<img id="image" src="pics/gameImage.gif" onClick = "score++" style="position:absolute; left: 400; top: 100;"/></a>
</div>
</body>
</html>
There are a handful of things wrong with your code:
1) Your <img> tags are ended with a stray, unneeded </a> tag.
2) In your <img> tag, you should change to onClick = "play();"
3) I don't believe javascript supports the global keyword in that way.
4) To change CSS style, try this:
firstDiv.style.display = 'none';
game.style.display = 'block';
5) You cannot display javascript variables in this fashion: <p>"Score: " + score</p>...not to mention there is no declared variable 'score' to begin with!
Keep working at it, you only get better with practice.
Tyr this
<script>
var score = 0;
var left=400;
var top = 100;
function play() {
var game = document.getElementById('game');
var firstDiv = document.getElementById('firstDiv');
var height = window.innerHeight;
var width = window.innerWidth;
firstDiv.style.display='none';
game.style.display='block';
setInterval("move()", 1000);
}
function move() {
var randomNumberX=Math.floor(Math.random()*11)-5;
var randomNumberY=Math.floor(Math.random()*11)-5;
left= left+randomNumberX;
top = top+randomNumberY;
var im= document.getElementById('image');
im.style.left=left;
im.style.top=top;
}
How can I add a link for an image created using the following Javascript code. I tried some changes, but nothing worked.
Please change the following code to the code with a link. I want to link all images at http://idealbodyweights.com/.
<script type="text/javascript">
var image1 = new Image()
image1.src =="http://idealbodyweights.com/wp-content/uploads/2013/05/1.png"
var image2 = new Image()
image2.src = "http://idealbodyweights.com/wp-content/uploads/2013/05/2.png"
var image3 = new Image()
image3.src = "http://idealbodyweights.com/wp-content/uploads/2013/05/3.png"
var image4 = new Image()
image4.src = "http://idealbodyweights.com/wp-content/uploads/2013/05/4.png"
</script>
</head>
<body>
<p><img src="images/pentagg.jpg" width="720" height="90" name="slide" /></p>
<script type="text/javascript">
var step=4;
function slideit()
{
document.images.slide.src = eval("image"+step+".src");
if(step<4)
step++;
else
step=1;
setTimeout("slideit()",2500);
}
slideit();
</script>
I rewrote a little of your code so it doesn't use eval and so the <img> is fetched using document.getElementById.
...
<script type="text/javascript">
var imgsrc = [
'http://idealbodyweights.com/wp-content/uploads/2013/05/1.png', // 0
'http://idealbodyweights.com/wp-content/uploads/2013/05/2.png', // 1
'http://idealbodyweights.com/wp-content/uploads/2013/05/3.png', // 2
'http://idealbodyweights.com/wp-content/uploads/2013/05/4.png' // 3
],
imgcache = [], i;
for (i = 0; i < imgsrc.length; ++i) { // cache images
imgcache[i] = new Image();
imgcache[i].src = imgsrc[i];
}
</script>
</head>
<body>
<p><img src="images/pentagg.jpg"
width="720" height="90"
name="slide" id="slide" /></p>
<script type="text/javascript">
var step = -1, // set so first will be 0
img = document.getElementById('slide'); // get the <img>
function slideit() {
step = (step + 1) % imgsrc.length; // loop over 0, 1, 2, 3 (or more)
img.src = imgsrc[step]; // set src by array index
setTimeout(slideit, 2500); // repeat in 2500 ms
}
slideit();// start
</script>
...
Is it what you want? :D
<p>
<a href="http://idealbodyweights.com/">
<img src="images/pentagg.jpg" width="720" height="90" name="slide" />
</a>
</p>