I'm making a element that is randomly appearing on the screen using javascript. What would I do in order to add an image using javascript to the randomly generated element?
function addEnemy() {
var interval = 0.1;
if (iterations > 1500) {
interval = 5;
} else if (iterations > 1000) {
interval = 3;
} else if (iterations > 500) {
interval = 1;
}
if (getRandom(50) == 0) {
var elementName = "enemy" + getRandom(10000000);
var enemy = createSprite(elementName, getRandom(450), -40, 45, 45);
var enemiesDiv = document.getElementById("enemiesDiv");
var element = document.createElement("div");
element.id = enemy.element;
element.className = "enemy";
enemiesDiv.appendChild(element);
enemies[enemies.length] = enemy;
element.enemy.innerHTML
}
}
You can create a new img element, give it the source to your image, then append that img element to your element you created. (I would suggest using a more descriptive variable name than just "element")
The relevant code could look like this:
var myImage = document.createElement('img');
myImage.src = 'my_image.jpg';
element.appendChild(myImage);
A little bit too broad, but I think you could consider using the background property of your created div. Something like this:
function addEnemy() {
var interval = 0.1;
if (iterations > 1500) {
interval = 5;
} else if (iterations > 1000) {
interval = 3;
} else if (iterations > 500) {
interval = 1;
}
if (getRandom(50) == 0) {
var elementName = "enemy" + getRandom(10000000);
var enemy = createSprite(elementName, getRandom(450), -40, 45, 45);
var enemiesDiv = document.getElementById("enemiesDiv");
var element = document.createElement("div");
element.id = enemy.element;
element.className = "enemy";
// Here
element.style.backgroundImage = "url('img_enemy.png')";
enemiesDiv.appendChild(element);
enemies[enemies.length] = enemy;
element.enemy.innerHTML
}
}
Related
hi everyone!
i have a map with dots MAP which every 3 seconds shows a block with info
a function that is already in progress, and I want the function to stop when clicking on a point and display an infoblock for me(and i did it).
sorry in advance below is my code
// map with dots
var isActive = 0;
var isLoading = 1;
const count = document.querySelectorAll("[data-id]");//circle svg around dot
function removeClass() {
let infoCards = document.querySelectorAll("[data-info-id]");// info page name of the project
infoCards.forEach((el) => {
el.classList.remove("show");
});
}
function removeCircle() {
count.forEach((el) => {
el.style.display = "none";
});
}
function ready() {
function setAround(percent, idx) {
removeCircle();
let beforeElemIdx = idx === 0 ? count.length - 1 : idx - 1;
let beforeElem = document.querySelector(
'[data-id="' + beforeElemIdx + '"]'
);
let elem = document.querySelector('[data-id="' + idx + '"]');
elem.style.display = "block";
elem.classList.remove('active-circle');
beforeElem.style.display = "block";
const math = 2 * Math.PI * elem.r.baseVal.value;
elem.style.strokeDasharray = `${math} 1000`;
let a = math * (1 - percent / 100);
elem.style.strokeDashoffset = a;
if (percent >= 99.5) {
removeClass();
let infoShow = document.querySelector(`[data-info-id="${idx}"]`);
infoShow.classList.add("show");
isLoading++;
if (isLoading === count.length) {
isLoading = 0;
}
}
}
requestAnimationFrame(draw);
function draw(t) {
let idx = isLoading;
requestAnimationFrame(draw);
setAround((t / 30) % 100, idx);//timer 3sec
}
}
document.addEventListener("DOMContentLoaded", ready);
and i did this
var dots = document.querySelectorAll(".dota");
var infoCards = document.querySelectorAll("[data-info-id]");
let circle = document.querySelectorAll('[data-id]');
dots.forEach((el) => {
el.addEventListener('click', () => {
let idx = el.dataset.dota;
let circle = el.dataset.dota;
showInfo(idx);
addCircle(idx);
});
});
function showInfo(idx) {
removeClass();
let elem = document.querySelector(`[data-info-id='${idx}']`);
elem.classList.add('show');
}
function addCircle(idx) {
let circle = document.querySelector(`[data-id='${idx}']`);
circle.classList.add('active-circle');
}
and if u want my site pls dm me i'll send my github page
PUG CODE
TY ALL!
Have you tried making a condition into the drawing function that pauses it?
If it's paused you can call another function that will draw the info of the specific dot only once and then create a condition in which it will resume the drawing normally.
When I used drawing function I've simply added a bool variable that stored if paused or not in the recursive function.
I have a big problem with images in javascript embedded aplications. I want make a preload image but I don't know how the browser works.
See this simple example: code
var colors = [
"http://www.robolaranja.com.br/wp-content/uploads/2014/10/Primeira-imagem-do-filme-de-Angry-Birds-%C3%A9-revelada-2.jpg",
"http://imguol.com/c/noticias/2013/12/13/13dez2013---esta-imagem-mostra-a-nebulosa-de-caranguejo-um-iconico-remanescente-de-supernova-na-nossa-galaxia-vista-do-observatorio-espacial-herschel-e-do-telescopio-hubble-uma-nuvem-de-gas-e-poeira-1386961235961_956x500.jpg",
"http://wallpaper.ultradownloads.com.br/121350_Papel-de-Parede-Imagem-Abstrata_1920x1200.jpg"
]
var currentDiv = "div2";
var count = 0;
var lenght = colors.length;
var timeForNextImage = 0;
var preloadOk = false;
setInterval(function() {
count ++;
if (count > lenght) count = 0;
var date = new Date();
var time = date.getTime();
if (time > (timeForNextImage - 3000) && preloadOk == false) {
preLoad();
} else if (time > timeForNextImage) {
play();
}
}, 300);
var play = function() {
if (currentDiv == "div2") {
$('#'+currentDiv).css("visibility", "visible");
} else {
$('#div2').css("visibility", "hidden");
}
var date = new Date();
timeForNextImage = date.getTime() + 10000;
preloadOk = false;
$("#lbl").text("div atual: "+currentDiv);
};
var preLoad = function() {
if (currentDiv == "div1") {
currentDiv = "div2";
} else {
currentDiv = "div1";
}
$("#" + currentDiv).css("background-image", 'url('+colors[count]+')');
preloadOk = true;
};
How you can look, I do a preload, in theory.. but, the browser only processes my image when I put it in the stage ?
What if I change the z-index attribute, it renders again?
You return preloadOK = true but the image doesn't load. That's not a preloader.
To make a preloader you can play with new Image() object or with load() event.
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(
"http://domain.tld/gallery/image-001.jpg",
"http://domain.tld/gallery/image-002.jpg",
"http://domain.tld/gallery/image-003.jpg"
)
See more
3 Ways to Preload Images with CSS, JavaScript, or Ajax
A simple way to preload an image is to just create an image tag and set the url as the src. You don't have to attach it to the DOM to make the request.
var preLoad = function() {
var img = new Image();
img.src = colors[count];
};
I need some javascript help. I am trying to set up two sprite animations with different frame rates in two separate div.
Here is a fiddle I started and i am very much stuck.
How do I combine the two div IDs into one statement? OR Should I be using ClassName in the statement to run on both divs?
http://jsfiddle.net/akwilinski/3t7d6qbL/1/
<div id="animate" class="animation"></div>
<div id="animate2" class="animation2"></div>
onload = function startAnimation() {
var frameHeight = 400;
var frames = 27;
var frame = 0;
var div = document.getElementById("animate");
setInterval(function () {
var frameOffset = (++frame % frames) * -frameHeight;
div.style.backgroundPosition = "0px " + frameOffset + "px";
}, 100);
}
Thank you for any assistance!
Simplest way to do this using the method you have already started using is to define 2 new variables, 1 for the second div and one for the second frame count. Then you can just add the call to your function.
Updated js:
onload = function startAnimation() {
var frameHeight = 400;
var frames = 27;
var frame = 0;
var div = document.getElementById("animate");
var div2 = document.getElementById("animate2");
setInterval(function () {
var frameOffset = (++frame % frames) * -frameHeight;
var frameOffset2 = (++frame % frames) * -frameHeight - 10;
div.style.backgroundPosition = "0px " + frameOffset + "px";
div2.style.backgroundPosition = "0px " + frameOffset + "px";
}, 100);
}
Fiddle
http://jsfiddle.net/f4v1vy7x/5/
I made a Can object to store the configuration for each can (so you can have different frameHeights, frames and frameRates.
I used window.requestAnimationFrame because it's far more efficient than setInterval. On each available frame I check whether it's time to animate based on each Can's set frame rate:
var Can = function( selector, frameHeight, frames, frameRate )
{
this.domCan = document.getElementById( selector );
this.frameHeight = frameHeight;
this.frames = frames;
this.frameRate = frameRate;
this.frame = 0;
};
onload = function startAnimation() {
var can1 = new Can( 'animate', 400, 27, 20 );
var can2 = new Can( 'animate2', 400, 27, 100 );
var cans = [ can1, can2 ];
window.requestAnimationFrame( function() {
can1.start = can2.start = new Date();
animate( cans );
} );
};
var animate = function( cans ) {
for( var i = 0; i < cans.length; i++ ) {
var now = new Date();
var can = cans[i];
if( now - can.start >= 1000 / can.frameRate ) {
can.start = now;
var frameOffset = (++can.frame % can.frames) * -can.frameHeight;
can.domCan.style.backgroundPosition = "0px " + frameOffset + "px";
}
}
window.requestAnimationFrame( function() {
animate( cans );
} );
}
You could do something like this:
var div = document.getElementById("animate");
var div2 = document.getElementById("animate2");
function anim(div) {
setInterval(function () {
var frameOffset = (++frame % frames) * -frameHeight;
div.style.backgroundPosition = "0px " + frameOffset + "px";
}, 100);
}
anim(div);
anim(div2);
You could then pass in additional parameters like frameHeight, frame, and frames to further customize each animation.
I am having a problem with craftyJS. I made a ship that shoots lasers, but I want the lasers to destroy an entity when it collides with it. I already tried to do this, but it don't work. Here is my code:
Crafty.init(1340,650, document.getElementById('game'));
Crafty.defineScene("gameStart", function() {
function newAlien(){
var random = Math.floor(Math.random() * 4) + 1;
switch(random){
case 1:
var alien = Crafty.e("2D, DOM, Image, Collision")
.image("alien1.png");
alien.x = ship.x;
alien.y = 20
break;
case 2:
var alien = Crafty.e("2D, DOM, Image, Collision")
.image("alien2.png");
alien.x = ship.x;
alien.y = 20;
break;
case 3:
var alien = Crafty.e("2D, DOM, Image, Collision")
.image("alien3.png");
alien.x = ship.x;
alien.y = 20;
break;
case 4:
var alien = Crafty.e("2D, DOM, Image, Collision")
.image("alien4.png");
alien.x = ship.x;
alien.y = 20;
break;
}
}
function newLaser(){
var laser = Crafty.e("2D, DOM, Image, Collision")
.image("laser.png")
.collision()
.onHit("alien", function(){
laser.destroy();
alien.destroy();
});
laser.y = 510;
laser.x = ship.x + 40;
var moveLaser = setInterval(function(){
if(laser.y < 1){
clearInterval(moveLaser);
laser.destroy();
} else {
laser.y = laser.y - 4;
}
}, 1);
}
function checkBorder(){
if(ship.x < 0 || ship.x > 1250){
Crafty.enterScene("gameStart");
}
}
function goLeft(){
var goLeftCount = 65;
var goLeftInterval = setInterval(function(){
if(goLeftCount === 0){
clearInterval(goLeftInterval);
checkBorder();
} else {
ship.x = ship.x - 1;
goLeftCount -= 1;
}
}, 1);
}
function goRight(){
var goRightCount = 65;
var goRightInterval = setInterval(function(){
if(goRightCount === 0){
clearInterval(goRightInterval);
checkBorder();
} else {
ship.x = ship.x + 1;
goRightCount -= 1;
}
}, 1);
}
var ship = Crafty.e("2D, DOM, Image, Bind")
.image("ship.png")
.bind('KeyDown', function(e) {
if(e.key == Crafty.keys['LEFT_ARROW']) {
goLeft();
} else if (e.key == Crafty.keys['RIGHT_ARROW']) {
goRight();
} else if(e.key == Crafty.keys['SPACE']) {
newLaser();
}
});
ship.y = 520;
ship.x = 600;
newAlien();
});
Crafty.enterScene("gameStart");
Can anyone please tell me what are the problems with my code?
One problem: when you try to destroy the alien, the alien variable isn't actually in scope. (You've declared it in a different function.) So there's no way alien.destroy(); will work.
Second problem: the function you pass to .onHit("alien", callback) will only be run when the laser hits an entity with the "alien" component. It has no idea what variable name you assigned the entity. However, the callback function will be passed information about what entities it's colliding with, and you can use that to resolve the collision.
I'm using this Code to show the current progress in my progressbar:
var rotatingTextElement;
var rotatingText = new Array();
var ctr = 0;
function initRotateText() {
rotatingTextElement = document.getElementById("percent");
rotatingText[0] = rotatingTextElement.innerHTML;
rotatingText[1] = "5%";
rotatingText[2] = "10%";
rotatingText[3] = "15%";
rotatingText[4] = "20%";
rotatingText[5] = "25%";
rotatingText[6] = "30%";
rotatingText[7] = "35%";
rotatingText[8] = "40%";
rotatingText[9] = "45%";
rotatingText[10] = "50%";
rotatingText[11] = "55%";
rotatingText[12] = "60%";
rotatingText[13] = "65%";
rotatingText[14] = "70%";
rotatingText[15] = "75%";
rotatingText[16] = "80%";
rotatingText[17] = "85%";
rotatingText[18] = "90%";
rotatingText[19] = "95%";
rotatingText[20] = "100%";
setInterval(rotateText, 500);
}
function rotateText() {
ctr++;
if(ctr >= rotatingText.length) {
ctr = 0;
}
rotatingTextElement.innerHTML = rotatingText[ctr];
}
window.onload = initRotateText;
It basicly writs a new percentage in span#percent every 500 miliseconds.
The problem is that after the progressbar has reached 100% it starts again with 0%, 5% and so on.
How can I check if the percentages in the array rotatingText till [20] were all shown and then stop the rotation?
Do this instead:
var rotatingTextElement = document.getElementById("percent");
var ctr = 0;
function rotateText() {
rotatingTextElement.innerHTML = ctr + "%";
ctr += 5;
if (ctr <= 100) {
window.setTimeout(rotateText, 500);
}
}
rotateText();
There are a few ways you can tidy this up. To answer your question, start by assigning the interval to a variable:
var rotator = null;
...
rotator = setInterval(rotateText, 500);
...
function rotateText() {
ctr++;
if(ctr >= rotatingText.length -1) {
clearInterval(rotator);
}
rotatingTextElement.innerHTML = rotatingText[ctr];
}
...
Then instead of resetting the iterator to 0 when it goes out of bounds, clear the interval so it stops changing the value. You'll need to add the -1 so that it stops on rotatingText[length-1] (the last element)