I'm working on trying to create a random image generator that will show a random image in Javascript. I've been able to make it show a random image via the Javascript math and using random variables. But sadly I'm still yet to be eligible to make my code repeat itself.
I know its probably very simplistic but as you know, we all start from somewhere. I've tried my best to compact my code and I have looked at other stackoverflow recourses but im still in no luck.
A quick overview of what happens, you are meant to be able to press a button and then, a selected random image is replaced by the current one.
What I want: to be able to press a button and then it will proceed to cycle through the random images 'x' times.
My code:
function imgRandom() {
var myImages1 = new Array();
myImages1[1] = "images/Random/Icon1.png";
myImages1[2] = "images/Random/Icon2.png";
myImages1[3] = "images/Random/Icon3.png";
myImages1[4] = "images/Random/Icon4.png";
myImages1[5] = "images/Random/Icon5.png";
myImages1[6] = "images/Random/Icon6.png";
myImages1[7] = "images/Random/Icon7.png";
myImages1[8] = "images/Random/Icon8.png";
myImages1[9] = "images/Random/Icon9.png";
myImages1[10] = "images/Random/Icon10.png";
myImages1[11] = "images/Random/Icon11.png";
myImages1[12] = "images/Random/Icon12.png";
myImages1[13] = "images/Random/Icon13.png";
myImages1[14] = "images/Random/Icon14.png";
myImages1[15] = "images/Random/Icon15.png";
myImages1[16] = "images/Random/Icon16.png";
myImages1[17] = "images/Random/Icon17.png";
myImages1[18] = "images/Random/Icon18.png";
myImages1[19] = "images/Random/Icon19.png";
myImages1[20] = "images/Random/Icon20.png";
myImages1[21] = "images/Random/Icon21.png";
myImages1[22] = "images/Random/Icon22.png";
myImages1[23] = "images/Random/Icon23.png";
var rnd = Math.floor(Math.random() * myImages1.length);
if (rnd == 0) {
rnd = 1;
}
document.getElementById("gen-img").src = myImages1[rnd];
}
<center>
<p>
<img id="gen-img" class="character-image" src="images/QuestionMark.png" style="width:180px;height:310px;">
</p>
<p>
<input type="button" class="button" value="Choose" onclick="setTimeout(imgRandom, 3000);" />
</p>
</center>
I hope this isn't too confusing, i'll be active for a long time if you're able to help! Thanks,
David.
I refactored your code a bit with an possible approach Here's the fiddle: https://jsfiddle.net/mrlew/d2py2jvb/
I commented with some explanations.
/* some flags you can set */
var timesTocycle = 10;
var totalImagesToCreate = 23;
var timeBetweenCycle = 3000;
/* global variables */
var allMyImages = [];
var timesCycled = 0;
/*
function to create your images path.
Called once when you load your page.
*/
function createMyImages(total) {
for (var i=0; i<total;i++) {
var imageNumber = i+1;
var path = getImagePath(imageNumber);
allMyImages.push(path);
}
}
/* separated your path getter */
function getImagePath(imageNumber) {
return "images/Random/Icon" + imageNumber + ".png";
}
/* this is the function called when you press the button and when one cycle ends */
function triggerRandomImage() {
if (timesCycled >= timesTocycle) return;
setTimeout(displayRandomImage, timeBetweenCycle);
}
/* random integer javascript function */
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
/* function called on setTimeout */
function displayRandomImage() {
var rnd = getRandomInt(0,allMyImages.length-1);
var imageToDisplayPath = allMyImages[rnd];
document.getElementById("gen-img").src = imageToDisplayPath;
timesCycled++;
triggerRandomImage();
/* debug info */
document.getElementById('info').innerText = "(showing: " + imageToDisplayPath + ", cycle: " + timesCycled + ", max: " + timesTocycle + ")";
}
/* call this function to populate the allMyImages array */
createMyImages(totalImagesToCreate);
I believe what you want is for loop. Let me demonstrate with your code:
var count = 10; //number of times to run the for loop
for (i = 0; i < count; i++){
var rnd = Math.floor(Math.random() * myImages1.length);
if (rnd == 0) {
rnd = 1;
}
document.getElementById("gen-img").src = myImages1[rnd];
}
The above code would run the randomizing bit 10 times (= 10 images). Now, I have not tested it yet, but I believe that the images would flash by really quickly. Also, unrelated to the question you may want to read about Javascript arrays.
Maybe I am not understanding this right or I am just writing something wrong. I am making an incremental game and am trying to figure out total dps which then I can change how gold is generated
This is the line of HTML I am trying to use the function with.
Total DPS:<span id="dps">0</span>
This is the javascript
function dps(){
dps = aadmg + daggerdmg + sworddmg;
document.getElementById("dps").innerHTML = dps;
};
function damageClick(number){
damage = damage + number;
document.getElementById("damage").innerHTML = damage;
gold =gold +1;
document.getElementById("gold").innerHTML = gold;
xp = damage * 2;
document.getElementById("xp").innerHTML = xp;
};
var aadmg = 0;
function buyAA(){
var aaCost = Math.floor(10 * Math.pow(1.1,aadmg));
if(gold >= aaCost){
aadmg = aadmg + 1;
gold = gold - aaCost;
document.getElementById("aadmg").innerHTML = aadmg;
document.getElementById("gold").innerHTML = gold;
};
var nextCost = Math.floor(10 * Math.pow(1.1,aadmg));
document.getElementById('aaCost').innerHTML = nextCost;
};
function buyDagger(){
var daggerCost = Math.floor(300 * Math.pow(1.1,daggerdmg));
if(gold >= daggerCost){
daggerdmg = daggerdmg + 5;
gold = gold - daggerCost;
document.getElementById("daggerdmg").innerHTML = daggerdmg;
document.getElementById("gold").innerHTML = gold;
};
var nextCost = Math.floor(300 * Math.pow(1.1,daggerdmg));
document.getElementById('daggerCost').innerHTML = nextCost;
};
var sworddmg = 0;
function buySword(){
var swordCost = Math.floor(500 * Math.pow(1.1,sworddmg));
if(gold >= swordCost){
sworddmg = sworddmg + 7;
gold = gold - swordCost;
document.getElementById("sworddmg").innerHTML = sworddmg;
document.getElementById("gold").innerHTML = gold;
};
var nextCost = Math.floor(500 * Math.pow(1.1,sworddmg));
document.getElementById('swordCost').innerHTML = nextCost;
};
My thought was that I have function dps used in the html and then it should equal aadmg + daggerdmg + sworddmg. I am getting the element dps with the document.getElementByID("dps").innerHTML = dps;. I have also tried adding getElement for all the dmg's as well. I am confused on how to obtain those numbers from the HTML and then add them together and display them.
You have a suicide function. When you have called the dps function once, it will have replaced itself with the value that you calculate. The next time that you try to call it, the dps identifier doesn't point to the function any more, so the code will crash.
Use a different variable in the function (and make it local by using the var keyword):
function dps(){
var x = aadmg + daggerdmg + sworddmg;
document.getElementById("dps").innerHTML = x;
};
(It would work just to make it local, but there is no good reason to use a local variable by the same name as the function.)
I think you're missunderstanding how functions are called in javascript. They are not called just because they have the same name/id as an html-element.
You would need something that triggers your calculations. A button for example.
A button could trigger your function like so:
<button id="myButton">clickme to calulate</button>
<script>
document.getElementById('myButton').addEventListener("click", function(){
dps();
});
</script>
Then your function dps() would have to look like that:
function dps(){
var x = aadmg + daggerdmg + sworddmg;
document.getElementById("dps").innerHTML = x;
};
But you should refactor your code to have an object that saves and serves all the data you need, instead of having plain global variables.
I have a problem I can not solve probably due to exhaustion. In my page I have two boxes in which pressing the "start" button changes the background color randomly without repetition. At first it worked then I changed some things and it no longer works as before. Sometimes I do not make colors appear in the array equal on the two panes. Here is my code
function go(){
var random = Math.floor((Math.random() * colori.length) + 0);
var t = Math.floor((Math.random() * colori.length) + 0);
var sx = document.getElementById("sx");
var dx = document.getElementById("dx");
var btngo = document.getElementById("go");
document.getElementById("scritta").innerHTML = random;
document.getElementById("scrittaU").innerHTML = t;
dx.style.backgroud = colori[random];
sx.style.backgroud = colori[t];
if(random == t){
alert("random:"+random+" " +"t"+t);
alert(colori.splice(random,1));
random = Math.floor((Math.random() * colori.length) + 0);
dx.style.background = colori[t];
sx.style.background = colori[random];
colori.splice(random,1);
colori.splice(t,1);
}
dx.style.background = colori[t];
sx.style.background = colori[random];
colori.splice(random,1);
colori.splice(random-1,1);
btngo.disabled=true;
}
dx.style.backgroud = colori[random];
sx.style.backgroud = colori[t];
Do you mean .background?
So I'm a newbie and should obviously spend time in the tuts, but I'm looking for a quick answer. Basically, I've created a grid of movie clips with AS3. When I 'preview' the flash (as a flash or HTML) it shows up fine. Success. Yet, the stage remains empty.
Q1) Will the stage remain empty as I have used AS3 to dynamically 'draw' the grid of mc's? Or is there a slit of code I am missing to make this baby show up on the stage?
Q2) I've managed to use alpha to make the MC's 'fade' on hover - but I want to make them change color (to red) when hovered over. I've searched everywhere and can't seem to find the right script.
Here is my code:
var stage = new createjs.Stage("canvas");
var image = new createjs.Bitmap("images/square.png");
stage.addChild(image);
createjs.Ticker.addEventListener("tick", handleTick);
function handleTick(event) {
image.x += 10;
stage.update();
}
var x0:Number = 0;
var y0:Number = 0;
var nt:Number = 72;
var nc = 10;
var vd:Number = 12;
var hd:Number = 12;
for (var i = 1; i <= nt; i++) {
var mc = this.attachMovie("square", "square" + i, i);
var aprox = Math.floor((i - 1) / nc);
mc._x = x0 + hd * ((i - aprox * nc) - 1);
mc._y = y0 + aprox * vd;
mc.useHandCursor = true;
// fade in
mc.onRollOver = function()
{
this.onEnterFrame = function()
{
if (this._alpha > 0) {
this._alpha -= 10;
} else {
this._alpha = 0;
delete this.onEnterFrame;
}
};
};
// fade out
mc.onRollOut = function()
{
this.onEnterFrame = function()
{
if (this._alpha < 100) {
this._alpha += 10;
} else {
this._alpha = 100;
delete this.onEnterFrame;
}
};
};
}
Thanks in advance - sorry I am a noob.
This will never work. 1/3 of your code is in AS3, 2/3 in AS2. Considering you haven't been thrown any error, I assume you exported it as AS2.
I want to animate (transition) from 1 color to another in raw javascript.
I dont want to use any framework (jquery, mootools) or css3. plain raw javascript.
I have been really having trouble to do this, can someone help me out ? :)
maybe something like this:
lerp = function(a, b, u) {
return (1 - u) * a + u * b;
};
fade = function(element, property, start, end, duration) {
var interval = 10;
var steps = duration / interval;
var step_u = 1.0 / steps;
var u = 0.0;
var theInterval = setInterval(function() {
if (u >= 1.0) {
clearInterval(theInterval);
}
var r = Math.round(lerp(start.r, end.r, u));
var g = Math.round(lerp(start.g, end.g, u));
var b = Math.round(lerp(start.b, end.b, u));
var colorname = 'rgb(' + r + ',' + g + ',' + b + ')';
el.style.setProperty(property, colorname);
u += step_u;
}, interval);
};
You can play around an try it out as a jsfiddle or check out the full working example below. You might want to improve this by using HSL/HSV colors, which gives you a prettier transition, but i'll leave that up to you.
<html>
<head>
<title>Fade</title>
<style type="text/css">
#box {
width: 100px;
height: 100px;
background-color: rgb(255,0,0);
}
</style>
</head>
<body>
<div id="box"></div>
<script type="text/javascript" charset="utf-8">
// linear interpolation between two values a and b
// u controls amount of a/b and is in range [0.0,1.0]
lerp = function(a,b,u) {
return (1-u) * a + u * b;
};
fade = function(element, property, start, end, duration) {
var interval = 10;
var steps = duration/interval;
var step_u = 1.0/steps;
var u = 0.0;
var theInterval = setInterval(function(){
if (u >= 1.0){ clearInterval(theInterval) }
var r = parseInt(lerp(start.r, end.r, u));
var g = parseInt(lerp(start.g, end.g, u));
var b = parseInt(lerp(start.b, end.b, u));
var colorname = 'rgb('+r+','+g+','+b+')';
el.style.setProperty(property, colorname);
u += step_u;
}, interval);
};
// in action
el = document.getElementById('box'); // your element
property = 'background-color'; // fading property
startColor = {r:255, g: 0, b: 0}; // red
endColor = {r: 0, g:128, b:128}; // dark turquoise
fade(el,'background-color',startColor,endColor,1000);
// fade back after 2 secs
setTimeout(function(){
fade(el,'background-color',endColor,startColor,1000);
},2000);
</script>
</body>
</html>
Here is also my solution:
<html><head>
<script type="text/javascript">
<!--
function animate(id,color0,color1,duration){
//public attributes
this.elem = document.getElementById(id);
//private attributes
var r0= parseInt(color0.substring(0,2),16);
var g0= parseInt(color0.substring(2,4),16);
var b0= parseInt(color0.substring(4,6),16);
var r1= parseInt(color1.substring(0,2),16);
var g1= parseInt(color1.substring(2,4),16);
var b1= parseInt(color1.substring(4,6),16);
var wait = 100; //100ms
var steps = duration/wait;
var rstep = (r1 - r0) / (steps);
var gstep = (g1 - g0) / (steps);
var bstep = (b1 - b0) / (steps);
var self = this;
//public functions
this.step = function() {
steps--;
if ( steps>0 ) {
r0 = Math.floor(r0 + rstep);
g0 = Math.floor(g0 + gstep);
b0 = Math.floor(b0 + bstep);
elem.style.backgroundColor = 'rgb('+r0+','+g0+','+b0+')';
//alert(steps + ' ; ' + elem.style.backgroundColor);
window.setTimeout(function(){self.step();}, wait);
} else {
elem.style.backgroundColor = '#'+color1;
}
}
step();
//alert(this.r0);
}
//-->
</script>
</head><body>
<div id="anim" style="width:100px; height:100px; background-color:#ff0000"></div>
<input type="button" onclick="animate('anim','1122ff','ff2211',1000)" value="test" />
</body>
</html>
html at pastebin, how to call the timeout function - see for example 1, 2
if canvas would be ok you could try doing it like this ;)
var context = document.getElementsByTagName('canvas')[0].getContext('2d');
var hue = 0;
function bgcolor() {
hue = hue + Math.random() * 3 ;
context.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
context.fillRect(0, 0, context.canvas.width, context.canvas.height);
}
setInterval(bgcolor, 20 );
Yes ;) it`s not perfect and just an excample but give it a try. Here is the complete pen on codepen.
One way might be to use setTimeout to call some function which incrementally changes the colour (I'm assuming background-color) by some small amount each time it's called. At each iteration, just check to see if you've arrived at your target colour and if not, increase or decrease your RGB value as necessary.