Creating an object generator - javascript

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.

Related

Having trouble changing shape of confetti

I've found this codepen that I'm integrating on a small website I have for a project. I don't want to put too much time into it, so I'll just be using a codepen I found. I'll do some adjustments to it, like the shape.
I managed to implement it, but now I'm having trouble to change the colors and the shape of the confetti.
The colors are completely random and I'd love for this to just be simple.
Also, I can't seem to be able to change the shape. I can only adjust the size.
If anyone here feels like giving me a nudge in the right direction, that'd be great!
'use strict';
// If set to true, the user must press
// UP UP DOWN ODWN LEFT RIGHT LEFT RIGHT A B
// to trigger the confetti with a random color theme.
// Otherwise the confetti constantly falls.
var onlyOnKonami = false;
$(function() {
// Globals
var $window = $(window)
, random = Math.random
, cos = Math.cos
, sin = Math.sin
, PI = Math.PI
, PI2 = PI * 2
, timer = undefined
, frame = undefined
, confetti = [];
// Settings
var konami = [38, 38, 40, 40, 37, 39, 37, 39, 66, 65]
, pointer = 0;
var particles = 150
, spread = 40
, sizeMin = 3
, sizeMax = 12 - sizeMin
, eccentricity = 10
, deviation = 100
, dxThetaMin = -.1
, dxThetaMax = -dxThetaMin - dxThetaMin
, dyMin = .13
, dyMax = .18
, dThetaMin = .4
, dThetaMax = .7 - dThetaMin;
var colorThemes = [
function() {
return color(200 * random()|0, 200 * random()|0, 200 * random()|0);
}, function() {
var black = 200 * random()|0; return color(200, black, black);
}, function() {
var black = 200 * random()|0; return color(black, 200, black);
}, function() {
var black = 200 * random()|0; return color(black, black, 200);
}, function() {
return color(200, 100, 200 * random()|0);
}, function() {
return color(200 * random()|0, 200, 200);
}, function() {
var black = 256 * random()|0; return color(black, black, black);
}, function() {
return colorThemes[random() < .5 ? 1 : 2]();
}, function() {
return colorThemes[random() < .5 ? 3 : 5]();
}, function() {
return colorThemes[random() < .5 ? 2 : 4]();
}
];
function color(r, g, b) {
return 'rgb(' + r + ',' + g + ',' + b + ')';
}
// Cosine interpolation
function interpolation(a, b, t) {
return (1-cos(PI*t))/2 * (b-a) + a;
}
// Create a 1D Maximal Poisson Disc over [0, 1]
var radius = 1/eccentricity, radius2 = radius+radius;
function createPoisson() {
// domain is the set of points which are still available to pick from
// D = union{ [d_i, d_i+1] | i is even }
var domain = [radius, 1-radius], measure = 1-radius2, spline = [0, 1];
while (measure) {
var dart = measure * random(), i, l, interval, a, b, c, d;
// Find where dart lies
for (i = 0, l = domain.length, measure = 0; i < l; i += 2) {
a = domain[i], b = domain[i+1], interval = b-a;
if (dart < measure+interval) {
spline.push(dart += a-measure);
break;
}
measure += interval;
}
c = dart-radius, d = dart+radius;
// Update the domain
for (i = domain.length-1; i > 0; i -= 2) {
l = i-1, a = domain[l], b = domain[i];
// c---d c---d Do nothing
// c-----d c-----d Move interior
// c--------------d Delete interval
// c--d Split interval
// a------b
if (a >= c && a < d)
if (b > d) domain[l] = d; // Move interior (Left case)
else domain.splice(l, 2); // Delete interval
else if (a < c && b > c)
if (b <= d) domain[i] = c; // Move interior (Right case)
else domain.splice(i, 0, c, d); // Split interval
}
// Re-measure the domain
for (i = 0, l = domain.length, measure = 0; i < l; i += 2)
measure += domain[i+1]-domain[i];
}
return spline.sort();
}
// Create the overarching container
var container = document.createElement('div');
container.style.position = 'fixed';
container.style.top = '0';
container.style.left = '0';
container.style.width = '100%';
container.style.height = '0';
container.style.overflow = 'visible';
container.style.zIndex = '9999';
// Confetto constructor
function Confetto(theme) {
this.frame = 0;
this.outer = document.createElement('div');
this.inner = document.createElement('div');
this.outer.appendChild(this.inner);
var outerStyle = this.outer.style, innerStyle = this.inner.style;
outerStyle.position = 'absolute';
outerStyle.width = (sizeMin + sizeMax * random()) + 'px';
outerStyle.height = (sizeMin + sizeMax * random()) + 'px';
innerStyle.width = '100%';
innerStyle.height = '100%';
innerStyle.backgroundColor = theme();
outerStyle.perspective = '50px';
outerStyle.transform = 'rotate(' + (360 * random()) + 'deg)';
this.axis = 'rotate3D(' +
cos(360 * random()) + ',' +
cos(360 * random()) + ',0,';
this.theta = 360 * random();
this.dTheta = dThetaMin + dThetaMax * random();
innerStyle.transform = this.axis + this.theta + 'deg)';
this.x = $window.width() * random();
this.y = -deviation;
this.dx = sin(dxThetaMin + dxThetaMax * random());
this.dy = dyMin + dyMax * random();
outerStyle.left = this.x + 'px';
outerStyle.top = this.y + 'px';
// Create the periodic spline
this.splineX = createPoisson();
this.splineY = [];
for (var i = 1, l = this.splineX.length-1; i < l; ++i)
this.splineY[i] = deviation * random();
this.splineY[0] = this.splineY[l] = deviation * random();
this.update = function(height, delta) {
this.frame += delta;
this.x += this.dx * delta;
this.y += this.dy * delta;
this.theta += this.dTheta * delta;
// Compute spline and convert to polar
var phi = this.frame % 7777 / 7777, i = 0, j = 1;
while (phi >= this.splineX[j]) i = j++;
var rho = interpolation(
this.splineY[i],
this.splineY[j],
(phi-this.splineX[i]) / (this.splineX[j]-this.splineX[i])
);
phi *= PI2;
outerStyle.left = this.x + rho * cos(phi) + 'px';
outerStyle.top = this.y + rho * sin(phi) + 'px';
innerStyle.transform = this.axis + this.theta + 'deg)';
return this.y > height+deviation;
};
}
function poof() {
if (!frame) {
// Append the container
document.body.appendChild(container);
// Add confetti
var theme = colorThemes[onlyOnKonami ? colorThemes.length * random()|0 : 0]
, count = 0;
(function addConfetto() {
if (onlyOnKonami && ++count > particles)
return timer = undefined;
var confetto = new Confetto(theme);
confetti.push(confetto);
container.appendChild(confetto.outer);
timer = setTimeout(addConfetto, spread * random());
})(0);
// Start the loop
var prev = undefined;
requestAnimationFrame(function loop(timestamp) {
var delta = prev ? timestamp - prev : 0;
prev = timestamp;
var height = $window.height();
for (var i = confetti.length-1; i >= 0; --i) {
if (confetti[i].update(height, delta)) {
container.removeChild(confetti[i].outer);
confetti.splice(i, 1);
}
}
if (timer || confetti.length)
return frame = requestAnimationFrame(loop);
// Cleanup
document.body.removeChild(container);
frame = undefined;
});
}
}
$window.keydown(function(event) {
pointer = konami[pointer] === event.which
? pointer+1
: +(event.which === konami[0]);
if (pointer === konami.length) {
pointer = 0;
poof();
}
});
if (!onlyOnKonami) poof();
});
Look inside Confetto() it's just using a <div> inside another <div> and giving it random width, height, 3D rotation, etc., you should be able to manipulate innerStyle and/or outerStyle to your liking there.
Try adding something like this to make it rounded:
innerStyle.borderRadius = '100%';
Try something like this to make it squared:
innerStyle.borderRadius = '0';
Or a combination:
innerStyle.borderRadius = '100% 0 0 100%';
You should be able to set any style property you need, by camel-casing the css name (.border for border, .borderBottom for border-bottom, .borderBottomColor for border-bottom-color, etc.). Check this list for ideas

Adding HTML rectangles with for loop in javascript

I would like to draw a 2 x 2 grid of blue rectangles on an HTML page, but my code does not draw anything. I create a fragment toAdd that I want to add later, and add divs to toAdd. I'm not quite sure where I went wrong, and when I tried to add a console.log() I could confirm that addSquares is being called. Do I need to add anything to the HTML file, or is there a mistake in this code?
I also noticed that this code produces five divs: b0, b1, b2, b3, b1 (returns error) and I'm not sure what is wrong with my for loop.
dim = 2;
width = 50;
height = 50;
// add the squares
function addSquares()
{
var toAdd = document.createDocumentFragment();
for(var i = 0; i < dim; i++)
{
for(var j = 0; j < dim; j++)
{
var label = j + i * dim;
var name = "b" + label;
console.log(name)
var div = document.createElement(name);
div.style.width = width + "px";
div.style.height = height + "px";
div.style.left = width * j + "px";
div.style.top = height * i + "px";
div.style.position = "absolute";
div.style.color = "blue";
toAdd.appendChild(div);
}
}
document.appendChild(toAdd);
}
So it appears that there's two issues. The first being that you need to change:
document.appendChild(toAdd);
to
document.body.appendChild(toAdd);
Your second issue is that your using the wrong CSS styling declaration. Your divs are in the DOM but don't have a backgroundColor assigned to them, which in turn gives the illusion that they're not there. So instead of color use backgroundColor.
dim = 2;
width = 50;
height = 50;
// add the squares
function addSquares()
{
var toAdd = document.createDocumentFragment();
for(var i = 0; i < dim; i++)
{
for(var j = 0; j < dim; j++)
{
var label = j + i * dim;
var name = "b" + label;
console.log(name)
var div = document.createElement(name);
div.style.width = width + "px";
div.style.height = height + "px";
div.style.left = width * j + "px";
div.style.top = height * i + "px";
div.style.position = "absolute";
div.style.backgroundColor = "blue";
toAdd.appendChild(div);
}
}
document.body.appendChild(toAdd);
}
addSquares();
I just wanted to point out a little trick to you...
You have this:
div.style.width = width + "px";
div.style.height = height + "px";
div.style.left = width * j + "px";
div.style.top = height * i + "px";
div.style.position = "absolute";
div.style.backgroundColor = "blue";
I believe can be written like this ES6:
div.style.cssText = `width: ${width + "px"};
height: ${height + "px"};
left: ${width * j + "px"};
top: ${height * i + "px"};
position: absolute;
backgroundColor: blue;`
As far as I know .cssText = will replace the existing inline...
To append the existing inline use .cssText +=
I'm sure this will help you in the long run.

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? )

remove elements in dom animation

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();

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