remove elements in dom animation - javascript

I try to delete some animated elements if they pass the screen height. For that an array will be checked in a for loop. The array have the id's of the created div's. Theoretically should all div's which have an y position which is higher than the screen height become removed and the values from the array deleted. But now it becomes every n element removed. Know anyone the issue for that? box = setInterval(newbox, 1000); affect the behaviour when I change the interval time.
fiddle
var cx = wwidth / 100;
var cy = wheight / 100;
var maxpos = cx * 80;
var speed;
var box;
var counter = 0;
var rectids = [];
var deleting;
function newbox() {
var allpositions = Array(0, cx * 25, cx * 50, cx * 75);
var rectpos = allpositions[Math.floor(Math.random() * allpositions.length)];
speed = 0;
var box = document.createElement('div');
counter++;
box.className = "game-btn";
box.id = 'n' + counter;
box.style.cssText = "top:" + speed + "px;left:" + rectpos + "px;width:" + cx * 25 + "px;height:" + cy * 10 + "px;position:absolute";
console.log(rectpos);
document.body.appendChild(box);
rectids.push(box.id);
}
function game() {
box = setInterval(newbox, 1000);
animaterects = setInterval(function () {
speed += cx / 300;
$(".game-btn").css("top", "+=" + speed + "px");
}, 10);
deleting = setInterval(function () {
for (var i = 0; i < rectids.length; i++) {
var x = $("#" + rectids[i]).position();
if (x.top > wheight) {
$("#" + rectids[i]).remove();
rectids.splice(rectids[i]);
}
}
}, 50);
}
game();

Related

How should I code this jQuery code in Javascript?

This exercise I need a function that moves the div randomly inside of the body when I click with the left button mouse.
I'm having some difficulties to swap this code(jquery) into javascript. How would it be?
var counter = 0;
var div = document.getElementsByClassName('a');
function click() {
if (counter < 1) {
var pos = makeNewPosition();
this.style.left = pos[1] + 'px';
this.style.top = pos[0] + 'px';
}
}
function makeNewPosition() {
// Get viewport dimensions (remove the dimension of the div)
var h = window.innerHeight = -50;
var w = window.innerWidth = -50;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh, nw];
}
<div onclick="click()" class="a">Click</div>
This is the jQuery that I wanted to code in javascript.
$(document).ready(function(){
var counter = 0;
$('.a').click( function () {
if (counter < 1 ) {
var pos = makeNewPosition();
this.style.left = pos[1] +'px';
this.style.top = pos[0] +'px';
}
});
});
function makeNewPosition(){
// Get viewport dimensions (remove the dimension of the div)
var h = $(window).height() - 50;
var w = $(window).width() - 50;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh,nw];
}
JavaScript:
window.addEventListener("load", function() {
var counter = 0,
div = document.querySelector(".a");
div.addEventListener("click", function() {
if (counter < 1) {
var pos = makeNewPosition();
this.style.left = pos[1] + 'px';
this.style.ltop = pos[0] + 'px';
}
counter++;
});
});
function makeNewPosition() {
// Get viewport dimensions (remove the dimension of the div)
var h = window.innerHeight -50;
var w = window.innerWidth -50;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh, nw];
}
.a {
position: absolute;
top: 100;
left: 100
}
<div class="a">Click</div>
Based on this jQuery:
$(function() {
var counter = 0;
$('.a').click(function() {
if (counter < 1) {
var pos = makeNewPosition();
$(this).css({
"left": pos[1] + 'px',
"top": pos[0] + 'px'
});
}
counter++;
});
});
function makeNewPosition() {
// Get viewport dimensions (remove the dimension of the div)
var h = $(window).height() - 50;
var w = $(window).width() - 50;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh, nw];
}
.a {
position: absolute;
top: 100;
left: 100
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="a">Click</div>
The most idiomatic way would be to first get a reference to the element
const div = document.getElementsByClassName('a')[0];
then add an event listener to the element
div.addEventListener('click', click); //Attach your handler function to the event

Creating an object generator

How do I create an object generator that will create a random square that is a random colour, size and position on the page? I think I have set up all the parameters but I can't put it all together.
//Size Generator
function getRndInteger(min, max) {
return Math.floor(Math.random() * (200 - 50 + 1) ) + 50;
}
var getSize = getRndInteger(50, 200);
//Colour Generator
function getRandomColor() {
var letters = '0123456789ABCDEF';
var colour = '#';
for (var i = 0; i < 6; i++) {
colour += letters[Math.floor(Math.random() * 16)];
}
return colour;
}
var colour = getRandomColor();
//Position Generator
function getPosition(min, max) {
return Math.floor(Math.random() * (600 - 0 + 1) ) + 0;
}
var getX = getPosition(0, 600);
var getY = getPosition(0, 600);
//Square Generator
function squareGenerator() {
var div = document.createElement("square");
div.style.backgroundColor = colour;
div.style.left = getX + "px";
div.style.top = getY + "px";
div.style.height = getSize + "px";
div.style.width = getSize + "px";
}
Where I am stuck is how to get this to show up on the page.
First of all, The created div will wrap around nothing, so You won't see it. a bypass would be setting the div.style.position to fixed.
Second of all, You need to append the div to the body, for example using: document.body.appendChild(div)
Third of all, You need to call the function, by placing the call: squareGenerator();
At last, when creating an element, use a valid HTML element, like div/section/article -> document.createElement('div'). It seems to be working with 'square' but I dont think all browsers will be that liberal.
//Size Generator
function getRndInteger(min, max) {
return Math.floor(Math.random() * (200 - 50 + 1) ) + 50;
}
var getSize = getRndInteger(50, 200);
//Colour Generator
function getRandomColor() {
var letters = '0123456789ABCDEF';
var colour = '#';
for (var i = 0; i < 6; i++) {
colour += letters[Math.floor(Math.random() * 16)];
}
return colour;
}
var colour = getRandomColor();
//Position Generator
function getPosition(min, max) {
return Math.floor(Math.random() * (200 - 0 + 1) ) + 0;
}
var getX = getPosition(0, 600);
var getY = getPosition(0, 600);
//Square Generator
function squareGenerator() {
var div = document.createElement("div");
div.style.backgroundColor = colour;
div.style.left = getX + "px";
div.style.top = getY + "px";
div.style.height = getSize + "px";
div.style.width = getSize + "px";
div.style.position='fixed';
document.body.appendChild(div);
}
squareGenerator();
You can see the desired square created at a random position.

dynamically positioning and animating images in JavaScript

I'm trying to animate an image dynamically by assigning a slope and a starting position randomly. I don't understand why my image is not appearing and when I take the comments off the animate function my code won't run. Everything works properly except the animate functions at the bottom. Any help will be graciously accepted!
//Generate the table for the game
function createTable(difficulty, mineArray)
{
document.getElementById("buttons").style.visibility="hidden";
var time = 0.00;
var row = 0;
var size = 0;
var Lives = 0;
var column = 0;
var input = "";
var completion = 0;
var minesLeft = 0;
if(difficulty == 0)
{
Lives = 5;
size = 600;
row = 30;
column = 20;
}
else if (difficulty == 1)
{
Lives = 3;
size = 600;
row = 30;
column = 20;
}
else if (difficulty == 2)
{
Lives = 5;
size = 1000;
row = 40;
column = 25;
}
else if (difficulty == 3)
{
Lives = 3
size = 1000;
row = 40;
column = 25;
}
for (var i = 0; i < size; i++)
{
if (mineArray[i] == 9)
{
minesLeft = minesLeft + 1;
}
}
//Header
var head = document.getElementById("header").style.width = "100%"
document.getElementById("lives").innerHTML = "Lives: " + Lives;
document.getElementById("title").innerHTML = "Minesweeper Bullet Hell";
document.getElementById("time").innerHTML = "Time: " + time;
document.getElementById("footer").innerHTML = "Mines Left: " + minesLeft;
var name = document.getElementById("Name");
document.getElementById("names").innerHTML = "Welcome " + name.value;
//Main div (where the game is played)
var main = document.getElementById("main");
main.style.width = "100%"
main.style.height = "100%"
//Table
var div = document.getElementById("Table");
div.style.position = "absolute";
div.style.left = "5%";
div.style.top = "5%";
div.style.right = "5%";
div.style.verticalAlign = "true";
if(difficulty == 1 || difficulty == 0)
{
div.style.height = "900";
div.style.width = "600";
}
if(difficulty == 1 || difficulty == 0)
{
div.style.height = "1000";
div.style.width = "625";
}
div.style.zIndex="1";
//Iterate through columns
while(completion < size)
{
for (var i = 0; i < column; i++)
{
var tr = document.createElement('tr');
//Iterate through rows
for(var j = 0; j < row; j++)
{
var place = completion;
var td = document.createElement('td');
//For smaller minefield
if (size == 600)
{
td.style.width = "30";
td.style.height = "auto";
td.style.color = "blue";
//Add an image
var img = document.createElement('img');
img.src = "grey square.png";
img.style.display = "block";
img.style.height = "30";
img.style.width = "30";
td.appendChild(img);
}
//For larger minefield
else
{
td.style.width = "25";
td.style.height = "auto";
td.style.color = "blue";
//Add an image
var img = document.createElement('img');
img.src = "grey square.png";
img.style.display = "block";
img.style.height = "25";
img.style.width = "25";
td.appendChild(img);
}
//If it is a mine
if (mineArray[completion] == 9)
{
td.style.backgroundColor = "grey";
td.style.color = "red";
}
td.style.border = "1px solid #666666"
td.style.textAlign = "center"
tr.appendChild(td);
completion++;
}
//Think about adding an event listener instead of overlaying buttons?
main.appendChild(tr);
}
var cells = document.getElementsByTagName("td");
for (var j = 0; i < row; j++)
{
cells[j].addEventListener("click", function () {
//show number
var thiscol = this.cellIndex;
var thisrow = this.parentNode.rowIndex;
console.log("Clicked at " + thisrow + thiscol);
var cell = main.rows[thisrow].cells[thiscol];
cell.innerHTML = mineArray[(thisrow * row) + thiscol];
})
}
}
setTimeout(function(){bullets()}, 100);
}
function bullets()
{
//randomly generate bullets including starting positions, direction, and trajectory
//Generate starting position
//Generate starting edge
var xpos;
var ypos;
var bullets;
var slopes
var edge = (Math.floor(Math.random() * 4) + 1)
var bullet = document.createElement('img')
var screen = docuemnt.getElementById("bullets");
bullet.src = "blank.png"
bullet.style.position = "relative"
switch (edge)
{
//left edge
case 1:
bullet.style.left = 20 + "px";
ypos = (Math.floor(Math.random() * 100) + 1);
bullet.style.top = ypos + "px";
bullet.id = "left";
break;
//top edge
case 2:
bullet.style.top = 20 + "px";
xpos = (Math.floor(Math.random() * 100) + 1);
bullet.style.right = xpos + "px";
bullet.id = "top"
break;
//right edge
case 3:
bullet.style.right = 20 + "px";
ypos = (Math.floor(Math.random() * 100) + 1);
bullet.style.top = ypos+ "px";
bullet.id = "right";
break;
//bottom edge
case 4:
bullet.style.bottom = 20 + "px";
xpos = (Math.floor(Math.random() * 100) + 1);
bullet.style.right = xpos + "px";
bullet.id = "bottom";
break;
}
//Get the slope
var xslope = (Math.floor(Math.random() * 20) + 5);
var yslope = (Math.floor(Math.random() * 20) + 5);
bullets.append(bullet);
slopes.append(xpos);
slopes.append(ypos);
screen.appendChild(bullet);
//startAnimation(slopes, bullets);
}
/*
function startAnimation(var slopes, var bullets)
{
var j = 0;
var posy;
var posx;
var id;
for(i = 0; i < bullets.size(); i++)
{
while(j < (j+2))
{
id = bullets(i).id;
switch(id)
{
case "left":
posx = bullets(i).style.left;
posy = bullets(i).style.top;
bullets(i).style.left = posx + slopes(j);
bullets(i).style.top = posy + slopes(j+1);
break;
case "top":
posx = bullets(i).style.left;
posy = bullets(i).style.top;
bullets(i).style.left = posx + slopes(j);
bullets(i).style.top = posy + slopes(j+1);
break;
case "right":
posx = bullets(i).style.right;
posy = bullets(i).style.top;
bullets(i).style.right = posx + slopes(j);
bullets(i).style.top = posy + slopes(j+1);
break;
case "bottom":
posx = bullets(i).style.left;
posy = bullets(i).style.bottom;
bullets(i).style.left = posx + slopes(j);
bullets(i).style.bottom = posy + slopes(j+1);
break;
}
j += 2;
}
}
}*/
Looks like there could be a few things making startAnimation stop your script. Here's a few changes to try out:
In your startAnimation function declaration try removing the var keyword before the parameters. So you'd have:
function startAnimation(slopes, bullets) {
Within the for loop, use the .length property to check the array length rather than .size() (see: Array.size() vs Array.length)
The while loop is creating an infinite loop, because the condition (j < (j+2)) will always be true, since it's checking the current value of j. It might be easier to swap this out with a for loop.
Next, within the function, replace the parentheses with square brackets for accessing array indexes (replace bullets(i) with bullets[i] and slopes(j) with slopes[j]. By using parentheses, the JavaScript interpreter is attempting to call these variables as functions. Since you already have a function called bullets I'd recommend renaming either the function or your local variable / parameter to avoid the complexity of dealing with variable name conflicts and scope (more info: What is the scope of variables in JavaScript? )

How to set onclick event in moving object in canvas?

How to set on click event in moving object in canvas? Also how to move the object bottom to top in canvas.I am newly in javascript i am going to develop the sample like when the page open, objects like square and circle randomly come from bottom of the page and move to top automatically.
You need to establish an array that will have your moving objects in it. When the onclick handler fires, check to see if the coordinates of the click are inside any of the objects in the array.
On each animation frame, move your objects up by subtracting some of the y coordinate from each object.
//width and height of canvas...
var rW = 400;
var rH = 500;
var coinImage = getCoinImage();
var coinsOnScreen = [];
var risingSpeed = 100; //pixels per second...
var coinSize = 75;
var lastAnimationTime = 0;
var howLongUntilNextCoin = 1000;
var nextCoinOnScreen = 0;
function doDraw() {
var can = document.getElementById("myCanvas");
can.width = rW;
can.height = rH;
var context = can.getContext("2d");
//Erase the canvas
context.fillStyle = "#FFFFFF";
context.fillRect(0, 0, rW, rH);
if (new Date().getTime() - nextCoinOnScreen > 0) {
var newX = Math.floor(Math.random() * rW) + 1;
var newY = rH + 50;
var newCoin = {
x: newX,
y: newY
};
coinsOnScreen.push(newCoin);
nextCoinOnScreen = new Date().getTime() + howLongUntilNextCoin;
}
//Now draw the coins
if (lastAnimationTime != 0) {
var deltaTime = new Date().getTime() - lastAnimationTime;
var coinRisePixels = Math.floor((deltaTime * risingSpeed) / 1000);
var survivingCoins = [];
for (var i = 0; i < coinsOnScreen.length; i++) {
var coin = coinsOnScreen[i];
coin.y = coin.y - coinRisePixels;
//the stl variable controlls the alpha of the image
if (coin.y + 50 > 0) {
context.drawImage(coinImage, coin.x, coin.y);
//this coin is still on the screen, so promote it to the new array...
survivingCoins.push(coin);
}
}
coinsOnScreen = survivingCoins;
}
lastAnimationTime = new Date().getTime();
//Wait, and then call this function again to animate:
setTimeout(function() {
doDraw();
}, 30);
}
function setupClickHandler() {
var can = document.getElementById("myCanvas");
//Here is the onclick handler
can.onclick = function(e) {
var x = e.clientX;
var y = e.clientY;
var survivingCoins = [];
for (var i = 0; i < coinsOnScreen.length; i++) {
var coin = coinsOnScreen[i];
//check to see if this coin has been clicked...
if (x > coin.x && x < coin.x + coinSize && y > coin.y && y < coin.y + coinSize) {
//ths coin will disappear because it is not inserted into the new array...
console.log("Coin was clicked!! " + x + " " + y);
} else {
survivingCoins.push(coin);
}
}
coinsOnScreen = survivingCoins;
};
}
doDraw();
setupClickHandler();
function getCoinImage() {
var image = new Image(50, 50);
image.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAYAAAAeP4ixAAAACXBIWXMAAAsTAAALEwEAmpwYAAAABGdBTUEAALGOfPtRkwAAACBjSFJNAAB6JQAAgIMAAPn/AACA6QAAdTAAAOpgAAA6mAAAF2+SX8VGAAAOWUlEQVR42mL8sYUBJ2BkhGAGKGZkQKUZYPz/QPo/gzwDE4MJEBswMDOoA7EUEAsD5bnAav8xfAfi9wx/GJ4x/GW4BWRfAuJTQLn7/xmBrP8Ie/9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nCIA2p7ACgABiIpA8bgMN8AUaeByWZ0CW/PwKYYPnx9mh/Rg0D8AwrLSBiSNPBsH6QKAxXVC3ABQbILP/Io3mA9VcBmI/8PQBHgAQQITHLyCecQfiNiD+CRu6BA0Y/ITOr4Im+0EOAdHgRQJoLV3k0okRWpzC9XBB8xPQrF9fEcUxUP1/IJ4K5LgA5c8RciZAADE+mog/4/1HarIA+XZAfheQZY5R1kPrBlBxyciE1ORGtgxpFcT/v4hZKwak1gO0v3QeSNcAOdsYocHNyIi/gAEIIFJXBx2CNmMSgbZlAS3Ugvf+YcM/jEhLP5jgqyfgIx7Ia0sYkZZKQX18D0jNBPJnQHs7RAOAACI1RhDjXsDaH0j5A1lRQLY9tHlIDvgJdPgxIL0CiNcCPfcWY20YETECEECUeASRbP4zaILaPUC+EZCtDmQD27oMvDhMBeWsh0BH3QTSF4BuOwBkX4LFCSO2RW5EeAQgwACQYpcXuHTdswAAAABJRU5ErkJggg==";
return image;
}
<canvas id="myCanvas"></canvas>

Angle of rotation of a needle following the cursor

Hello I am trying to write a simple program for fun.. But I am not able to get the angle of rotation and convert it into the number where the needle lands after it follows the crusor.I am letting the needle follow inside the dial. I am including my javascript code. Can anybody help me please?
function alienEye(x, y, size, append, img, theNum) {
var self = this;
var i = 0;
var myintID;
this.x = x;
this.y = y;
this.size = size;
//Create the Eye Dom Node using canvas.
this.create = function create(x, y, size, append) {
//Create dom node
var eye = document.createElement('canvas');
eye.width = size;
eye.height = size;
eye.style.position = 'relative';
eye.style.top = y + 'px';
eye.style.left = x + 'px';
document.getElementById(append).appendChild(eye);
//Get canvas
canvas = eye.getContext("2d")
radius = size / 2;
//draw eye
//canvas.beginPath();
//canvas.arc(radius, radius, radius, 0, Math.PI*2, true);
//canvas.closePath();
//canvas.fillStyle = "rgb(255,255,255)";
//canvas.fill();
//draw pupil
//canvas.beginPath();
//canvas.arc(radius, radius/2, radius/4, 0, Math.PI*2, true);
//canvas.closePath();
//canvas.fillStyle = "rgb(0,0,0)";
//canvas.fill();
//var img = new Image();
canvas.drawImage(img, - 20, - 20, 100, 100);
img.onload = function () {
canvas.drawImage(img, - 20, - 20, 100, 100);
}
img.src = 'Stuff/needle.png';
return eye;
}
//Rotate the Dom node to a given angle.
this.rotate = function (x) {
this.node.style.MozTransform = "rotate(" + x + "deg)";
this.node.style.WebkitTransform = "rotate(" + x + "deg)";
this.node.style.OTransform = "rotate(" + x + "deg)";
this.node.style.msTransform = "rotate(" + x + "deg)";
this.node.style.Transform = "rotate(" + x + "deg)";
}
this.letsBegin = function () {
//Update every 100 miliseconds
myintID = setInterval(function () {
//Math!
angleFromEye = Math.atan2((cursorLocation.y - self.my_y), cursorLocation.x - self.my_x) * (180 / Math.PI) + 90;
//Rotate
self.rotate(angleFromEye);
//Refresh own position every 25th time (in case screen is resized)
i++;
if (i > 25) {
self.locateSelf();
i = 0;
}
}, 20);
}
this.letsEnd = function () {
clearInterval(myintID);
}
this.locateSelf = function () {
this.my_x = this.node.offsetLeft + (this.size / 2);
this.my_y = this.node.offsetTop + (this.size / 2);
//If it has offsetParent, add em up to get the objects full position.
if (this.node.offsetParent) {
temp = this.node;
while (temp = temp.offsetParent) {
this.my_x += temp.offsetLeft;
this.my_y += temp.offsetTop;
}
}
}
//Call the node create function when the AlienEye Object is created.
this.node = this.create(x, y, size, append);
this.locateSelf();
//Now the node has been added to the page, lets figure out exact where
//it is relative to the documents top.
//Get the basic position
var cursorLocation = new function () {
this.x = 0;
this.y = 0;
//This function is called onmousemove to update the stored position
this.update = function (e) {
var w = window,
b = document.body;
this.x = e.clientX + (w.scrollX || b.scrollLeft || b.parentNode.scrollLeft || 0);
this.y = e.clientY + (w.scrollY || b.scrollTop || b.parentNode.scrollTop || 0);
}
//Hook onmousemove up to the above update function.
document.onmousemove = function (e) {
cursorLocation.update(e);
};
If that's all your code, all you need to do is call the functions.
I managed to get it running by adding this to the bottom of the script (the body element was given an ID of "body"):
var img = new Image();
img.src = "Stuff/needle.png";
var eye = new alienEye(40, 40, 50, "body", img, 20);
eye.letsBegin();
Edit:
Here's how I got the angle based off two points in my GameAPI. It's a bit verbose... the main angle code is at the bottom:
getAngle : function(point1X, point1Y, point2X, point2Y, hyp) {
//This function uses the arcsine to calculate the angle between
//the points, but only if necessary.
//This function includes some shortcuts for common angles.
if(point1Y == point2Y) {
if(point1X < point2X) return 0;
else return 180;
}
if(point1X == point2X) {
if(point1Y < point2Y) return 90;
else return 270;
}
var xDist = point1X - point2X;
var yDist = point1Y - point2Y;
if(xDist == yDist) {
if(point1X < point2X) return 45;
else return 225;
}
if(-xDist == yDist) {
if(point1X < point2X) return 315;
else return 135;
}
if(hyp==null)
hyp = Math.sqrt( xDist*xDist + yDist*yDist );
var D_TO_R = this.D_TO_R;
if(point1X<point2X) {
//console.log(Math.round(-Math.asin((point1Y-point2Y)/hyp) * D_TO_R));
return Game.Util.fixDirection(-Math.asin((point1Y-point2Y)/hyp) * this.D_TO_R);
} else {
//console.log(Math.round(Math.asin((point1Y-point2Y)/hyp) * D_TO_R + 180));
return Game.Util.fixDirection(Math.asin((point1Y-point2Y)/hyp) * this.D_TO_R+180);
}
}
(The D_TO_R is the constant 180/PI for radian/angle conversion. The Game.Util.fixDirection ensures that the angle is between 0 and 360 The hyp argument is an optional argument for if the hypothenuse of the right triangle is already known, as to save CPU cycles)

Categories