Add a Key Pair to an array in javascript? - javascript

I am currently using a piece of code that I have found online for drawing a diagram by a set of angles and lengths, the problem I am having is constructing the array on the fly.
The array that works fine is this
arr = [
{ angle: 0, h: 100 },
{ angle: 45, h: 100 },
{ angle: 90, h: 300 },
{ angle: 135, h: 100 },
{ angle: 180, h: 100 }
];
but I am struggling with the syntax to insert the information into an array to match this format, here is what I have so far but this causes me an error which I am not sure.
for( var i = 1; i < 42;i++) {
arr[i].angle = document.getElementById("1m2mangle"+i).value;
arr[i].h = document.getElementById("1m2mlength"+i).value};
}
Any suggestions would be much appreciated, here is the code for drawing the lines from the input array.
ctx.moveTo(pos.x, pos.y);
pos = getAngle(ctx, pos.x, pos.y, arr[i].angle, arr[i].h);
ctx.lineTo(pos.x, pos.y);
Thanks
--Revised Function --
function draw<%response.write(counter1)%>() {
var arr = [];
for( var i = 1; i < 42;) {
alert(document.getElementById("<%response.write(counter1)%>m2mangle"+i)).value);
arr.push({
angle: document.getElementById("<%response.write(counter1)%>m2mangle1").value, h: document.getElementById("<%response.write(counter1)%>m2mlength1").value});
i++;
}
var canvas = document.getElementById('curtainCanvas<%response.write(counter1)%>');
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.font = "20px Georgia";
var pos = { x: 15, y: 15 };
ctx.fillText(1,10,10);
for (var i = 0; i < arr.length; i++) {
// alert(pos.x);
ctx.moveTo(pos.x, pos.y);
pos = getAngle(ctx, pos.x, pos.y, arr[i].angle, arr[i].h);
ctx.lineTo(pos.x, pos.y);
ctx.fillText(i+2,pos.x, pos.y);
}
ctx.stroke();
}
}

This is how it's done with JS:
for( var i = 1; i < 42;i++) {
arr.push({
angle: document.getElementById("1m2mangle"+i).value,
h: document.getElementById("1m2mlength"+i).value
});
}
WE're basically pushing a new object into the end of the array, which is the structure you need in your case.

Related

player will sometimes phase through platforms in prototype of infinite runner game?

I'm coding an infinite runner game in javascript using the html5 canvas, and it's been going pretty well so far, but I have been getting the jump mechanism in place, and sometimes the player will phase through the platform they land on, which they shouldn't do, as i have code in place to prevent that. By the way, while the player will not be able to phase through the sides of the platforms in the finished game, I have no code in place to prevent it yet. This only happens on the platform one object. Any idea why it is doing this? My code is here-
const canvas = document.getElementById('gameframe')
const ctx = canvas.getContext('2d')
var player = {
y: 250,
x: 250,
w: 30,
h: 30
}
var plat1 = {
x: 250,
y: 350,
w: 250,
h: 300
}
var plat2 = {
x: 50,
y: 400,
w: 250,
h: 300
}
var plat3 = {
x: -200,
y: 375,
w: 250,
h: 300
}
var currentPlat = {
x: 1,
y: 1,
w: 1,
h: 1
}
function renderPlatforms() {
ctx.fillStyle = 'black';
ctx.rect(plat1.x, plat1.y, plat1.w, plat1.h);
ctx.rect(plat2.x, plat2.y, plat2.w, plat2.h);
ctx.rect(plat3.x, plat3.y, plat3.w, plat3.h);
ctx.fill();
plat1.x--;
plat2.x--;
plat3.x--;
if (plat1.x === 0 - plat1.w) {
plat1.x = 500;
}
if (plat2.x === 0 - plat2.w) {
plat2.x = 500;
}
if (plat3.x === 0 - plat3.w) {
plat3.x = 500;
}
}
function renderPlayer() {
ctx.rect(player.x, player.y, player.w, player.h)
ctx.fill();
}
function draw() {
getCurrentPlat();
doGravity();
ctx.beginPath();
ctx.clearRect(0, 0, canvas.width, canvas.height);
renderPlayer();
renderPlatforms();
ctx.fill();
setTimeout(draw, 3)
}
draw();
function getCurrentPlat() {
if (player.x + player.w >= plat1.x && player.x <= plat1.x + plat1.w) {
currentPlat.x = plat1.x;
currentPlat.y = plat1.y;
currentPlat.w = plat1.w;
currentPlat.h = plat1.h;
console.log('on platform one')
console.log()
}
if (player.x + player.w >= plat2.x && player.x <= plat2.x + plat2.w) {
currentPlat.x = plat2.x;
currentPlat.y = plat2.y;
currentPlat.w = plat2.w;
currentPlat.h = plat2.h;
}
if (player.x + player.w >= plat3.x && player.x <= plat3.x + plat3.w) {
currentPlat.x = plat3.x;
currentPlat.y = plat3.y;
currentPlat.w = plat3.w;
currentPlat.h = plat3.h;
}
}
function doGravity() {
if (player.y + 30 < currentPlat.y && jumping === false) {
player.y++;
}
}
var cntr = 0
var jumping = false
function jump() {
jumping = true;
if (cntr < 90) {
cntr++;
player.y--;
setTimeout(jump, 2);
} else {
function fls() {
jumping = false;
}
cntr = 0;
setTimeout(fls, 50)
}
}
<!DOCTYPE html>
<html>
<canvas width='500' height='500' id='gameframe' style='border-style: solid;'>Sorry, canvas is not supported for your browser. </canvas>
<button onclick='jump()'>jump</button>
<script src='script.js'></script>
</html>
Not sure if it was intentional but your platforms do overlap...
see it in the sample below
I did improve your code to use an array for the platforms instead of individual items, then we can loop platforms.forEach that should help you reduce the duplicate code, and adding many more platforms in the future will be very easy.
const canvas = document.getElementById('gameframe')
const ctx = canvas.getContext('2d')
var platforms = [
{x: 250, y: 50, w: 250,h: 301},
{x: 50, y: 100, w: 250,h: 302},
{x: -200, y: 75, w: 250,h: 303}
]
function renderPlatforms() {
platforms.forEach(function(p) {
ctx.beginPath();
ctx.rect(p.x, p.y, p.w, p.h);
ctx.fillText(p.x, p.x +5, p.y-5);
ctx.fillText(p.w + " / " +p.h, p.x +5, p.y+20);
ctx.stroke();
if (p.x-- === 0 - p.w) p.x = canvas.width;
})
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
renderPlatforms();
setTimeout(draw, 10)
}
draw();
<canvas width='500' height='150' id='gameframe' style='border-style: solid;'></canvas>
If you are going to overlap the platforms like that you have to change your logic and check if the player collides with any of the platforms your approach to only check against one (a current platform) is creating problems.
When troubleshooting games I find ctx.fillText() more helpful than the console.log() you can show on screen the values of the objects also quite often slowing down the game helps you see if the values really change when you expect them too change.

How do I stop a canvas animation when the same function is called again?

I am currently coding a website where, upon clicking a navigation link, HTML canvas draws a line to the relevant content box (I used markE's brilliant answer here https://stackoverflow.com/a/23941786 as a tutorial for the animation). I am in the process of animating these lines and I am running into the following issue / question:
How do I stop the first animation from completing when another link is clicked?
I have tried both creating a flag and cancelAnimationFrame in several iterations, to no joy.
Here's some simplified code, currently utilising a flag:
HTML
<div class="container">
<nav>
<ul>
<li>
About
</li>
<li>
Work
</li>
</ul>
</nav>
</div>
<canvas id="canvas" width="500" height="500"></canvas>
JavaScript
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var isRunning = false;
function draw(contentId) {
if (isRunning) return;
isRunning = true;
var t = 1;
var vertices = [];
function calcWaypoints(vertices) {
var waypoints = [];
for (var i = 1; i < vertices.length; i++) {
var pt0 = vertices[i - 1];
var pt1 = vertices[i];
var dx = pt1.x - pt0.x;
var dy = pt1.y - pt0.y;
for (var j = 0; j < 100; j++) {
var x = pt0.x + dx * j / 100;
var y = pt0.y + dy * j / 100;
waypoints.push({
x: x,
y: y
});
}
}
return (waypoints);
}
function animate() {
if (t < points.length - 1) {
window.requestAnimationFrame(animate);
}
ctx.beginPath();
ctx.moveTo(points[t - 1].x, points[t - 1].y);
ctx.lineTo(points[t].x, points[t].y);
ctx.stroke();
t++;
isRunning = false;
}
// Clear the canvas before drawing
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Assign coordinates
if (contentId == 'about') {
vertices.push({x: 50, y: 0}, {x: 50, y: 50});
vertices.push({x: 40, y: 60}, {x: 0, y: 60});
// Animate lines
ctx.lineCap = "round";
ctx.lineWidth = border;
ctx.strokeStyle = "green";
var points = calcWaypoints(vertices);
animate(points);
}
if (contentId == 'contact') {
vertices.push({x: 150, y: 0}, {x: 150, y: 50});
vertices.push({x: 160, y: 60}, {x: 300, y: 60});
vertices.push({x: 300, y: 70}, {x: 310, y: 70});
ctx.lineCap = "round";
ctx.lineWidth = border;
ctx.strokeStyle = "green";
var points = calcWaypoints(vertices);
animate(points);
}
}
Just to reiterate, in case I was unclear: when I've clicked on 'about' and then straight away click on 'contact', I would like the draw animation that was initialized when I first clicked on 'about' to completely stop (including clearing the canvas) and the 'contact' animation to start instead. At the moment, the 'contact' animation does start, but the 'about' animation insists on finishing as well. The same thing happens when I click on 'about' twice - the animation runs twice, simultaneously...
In case it helps anyone, I managed to solve it (there were some errors in logic and cancelAnimationFrame ended up doing what I needed rather than using a flag):
HTML
<div class="container">
<nav>
<ul>
<li>
About
</li>
<li>
Work
</li>
</ul>
</nav>
</div>
<canvas id="canvas" width="500" height="500"></canvas>
JavaScript
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var requestId;
function checkDraw(contentId) {
stopAnimation();
draw(contentId);
}
function stopAnimation(e) {
cancelAnimationFrame(requestId);
}
function draw(contentId) {
currentID = contentId;
var t = 1;
var vertices = [];
function calcWaypoints(vertices) {
var waypoints = [];
for (var i = 1; i < vertices.length; i++) {
var pt0 = vertices[i - 1];
var pt1 = vertices[i];
var dx = pt1.x - pt0.x;
var dy = pt1.y - pt0.y;
for (var j = 0; j < 100; j++) {
var x = pt0.x + dx * j / 100;
var y = pt0.y + dy * j / 100;
waypoints.push({
x: x,
y: y
});
}
}
return (waypoints);
}
function animate() {
if (t < points.length - 1) {
requestId = requestAnimationFrame(animate);
}
ctx.beginPath();
ctx.moveTo(points[t - 1].x, points[t - 1].y);
ctx.lineTo(points[t].x, points[t].y);
ctx.stroke();
t++;
}
// Clear the canvas before drawing
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Assign coordinates
if (contentId == 'about') {
vertices.push({x: 50, y: 0}, {x: 50, y: 50});
vertices.push({x: 40, y: 60}, {x: 0, y: 60});
// Animate lines
ctx.lineCap = "round";
ctx.lineWidth = border;
ctx.strokeStyle = "green";
var points = calcWaypoints(vertices);
animate(points);
}
if (contentId == 'contact') {
vertices.push({x: 150, y: 0}, {x: 150, y: 50});
vertices.push({x: 160, y: 60}, {x: 300, y: 60});
vertices.push({x: 300, y: 70}, {x: 310, y: 70});
ctx.lineCap = "round";
ctx.lineWidth = border;
ctx.strokeStyle = "green";
var points = calcWaypoints(vertices);
animate(points);
}
}
I hope this makes sense!

Canvas Snow Animation does not work

So a season specific question. I have made a basic animation to simulate some snow. The problem is that the snow only falls once and the screen stays black after that. I have followed a tutorial which put everything inside the window.onload(). THis seems not as good style to me so here is what i came up with:
let sky, ctx;
let W, H;
const maxSnow = 250;
const snow = [];
function init(){
sky = document.getElementById("sky");
ctx = sky.getContext("2d");
sky.width = W = window.innerWidth;
sky.height = H = window.innerHeight;
for(let i = 0; i < maxSnow; i++)
{
snow.push({
x: Math.random()*W, //x-coordinate
y: -50, //y-coordinate
radius: Math.random()*4+1, //radius
density: Math.random()*maxSnow //density
})
}
}
function draw()
{
ctx.clearRect(0, 0, W, H);
ctx.fillStyle = "rgba(255, 255, 255, 0.8)";
ctx.beginPath();
for(let i = 0; i < maxSnow; i++)
{
var flake = snow[i];
ctx.moveTo(flake.x, flake.y);
ctx.arc(flake.x, flake.y, flake.radius, 0, Math.PI*2, true);
}
ctx.fill();
update();
}
//Function to move the snowflakes
//angle will be an ongoing incremental flag. Sin and Cos functions will be applied to it to create vertical and horizontal movements of the flakes
var angle = 0;
function update()
{
angle += 0.01;
for(var i = 0; i < maxSnow; i++)
{
var p = snow[i];
//Updating X and Y coordinates
//We will add 1 to the cos function to prevent negative values which will lead flakes to move upwards
//Every particle has its own density which can be used to make the downward movement different for each flake
//Lets make it more random by adding in the radius
p.y += Math.cos(angle+p.density) + 1 + p.radius/2;
p.x += Math.sin(angle) * 2;
//Sending flakes back from the top when it exits
//Lets make it a bit more organic and let flakes enter from the left and right also.
if(p.x > W+5 || p.x < -5 || p.y > H)
{
if(i%3 > 0) //66.67% of the flakes
{
snow[i] = {x: Math.random()*W, y: -10, r: p.radius, d: p.density};
}
else
{
//If the flake is exitting from the right
if(Math.sin(angle) > 0)
{
//Enter from the left
snow[i] = {x: -5, y: Math.random()*H, r: p.radius, d: p.density};
}
else
{
//Enter from the right
snow[i] = {x: W+5, y: Math.random()*H, r: p.radius, d: p.density};
}
}
}
}
}
window.onload = function(){
init();
//animation loop
setInterval(draw, 33);
}
window.addEventListener('resize', function(){
sky.width = W = window.innerWidth;
sky.height = H = window.innerHeight;
}, false);
* {
margin: 0;
padding: 0;
}
body {
overflow: hidden;
background-color: rgba(0, 0, 0, 1);
}
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas id="sky"></canvas>
<script src="snow.js"></script>
</body>
</html>
Does anybody see what the problem is and why the particles are only falling once?
Thank you.
The is because when the snow flakes exit the screen you reset them to a wrong object.
You original object (and all methods) expect x,y,radius and density
But when you update the object you create x,y, r and d.
If you rename r and d to the correct names it works.
let sky, ctx;
let W, H;
const maxSnow = 250;
const snow = [];
function init(){
sky = document.getElementById("sky");
ctx = sky.getContext("2d");
sky.width = W = window.innerWidth;
sky.height = H = window.innerHeight;
for(let i = 0; i < maxSnow; i++)
{
snow.push({
x: Math.random()*W, //x-coordinate
y: -50, //y-coordinate
radius: Math.random()*4+1, //radius
density: Math.random()*maxSnow //density
})
}
}
function draw()
{
ctx.clearRect(0, 0, W, H);
ctx.fillStyle = "rgba(255, 255, 255, 0.8)";
ctx.beginPath();
for(let i = 0; i < maxSnow; i++)
{
var flake = snow[i];
ctx.moveTo(flake.x, flake.y);
ctx.arc(flake.x, flake.y, flake.radius, 0, Math.PI*2, true);
}
ctx.fill();
update();
}
//Function to move the snowflakes
//angle will be an ongoing incremental flag. Sin and Cos functions will be applied to it to create vertical and horizontal movements of the flakes
var angle = 0;
function update()
{
angle += 0.01;
for(var i = 0; i < maxSnow; i++)
{
var p = snow[i];
//Updating X and Y coordinates
//We will add 1 to the cos function to prevent negative values which will lead flakes to move upwards
//Every particle has its own density which can be used to make the downward movement different for each flake
//Lets make it more random by adding in the radius
p.y += Math.cos(angle+p.density) + 1 + p.radius/2;
p.x += Math.sin(angle) * 2;
//Sending flakes back from the top when it exits
//Lets make it a bit more organic and let flakes enter from the left and right also.
if(p.x > W+5 || p.x < -5 || p.y > H)
{
if(i%3 > 0) //66.67% of the flakes
{
snow[i] = {x: Math.random()*W, y: -10, radius: p.radius, density: p.density};
}
else
{
//If the flake is exitting from the right
if(Math.sin(angle) > 0)
{
//Enter from the left
snow[i] = {x: -5, y: Math.random()*H, radius: p.radius, density: p.density};
}
else
{
//Enter from the right
snow[i] = {x: W+5, y: Math.random()*H, radius: p.radius, density: p.density};
}
}
}
}
}
window.onload = function(){
init();
//animation loop
setInterval(draw, 33);
}
window.addEventListener('resize', function(){
sky.width = W = window.innerWidth;
sky.height = H = window.innerHeight;
}, false);
* {
margin: 0;
padding: 0;
}
body {
overflow: hidden;
background-color: rgba(0, 0, 0, 1);
}
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas id="sky"></canvas>
<script src="snow.js"></script>
</body>
</html>

How do i make fluid movement with arrows using javascript?

I am trying to make a game with where you can control a box with the arrow-keys but i am stuck. I have used this code before and it worked but now i det a error and i dont know how to fix it.
When this code works the player will lagg a lot and i want to make a fluid charactermovement how do i do that?
I would be very grateful if someone could hjempe me with both problems
the code i have so far is
var canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
var farge = ["blue", "darkorchid", "yellowgreen", "violet", "peru", "darkorange", "lightskyblue"];
var tileldig = Math.floor((Math.random() * 300) + 1);
var kuler = [
{r: 10, x: canvas.width/2, y: canvas.height-100, f: "red"},
//{r: 50, x: tileldig, y: 50, vx:0 , vy: 3, f: "green"},
]
var fiender = [
{r: 5, x: tileldig, y: 50, vx:0 , vy: 3, },
]
function bounceCircle () {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < kuler.length; i++) {
kuler[i].x += 0;
kuler[i].y += 0;
ctx.fillStyle = kuler[i].f;
ctx.beginPath();
ctx.arc(kuler[i].x, kuler[i].y, kuler[i].r, 2*Math.PI, 0);
ctx.closePath();
ctx.fill();
function tast (e) {
if (e.keyCode == 37) {
kuler[i].x -= 10;
};
if (e.keyCode == 39) {
kuler[i].x += 10;
};
if (e.keyCode == 38) {
kuler[i].y -= 10;
};
if (e.keyCode == 40) {
kuler[i].y += 10;
};
}
document.onkeydown = tast;
};
for (var i = 0; i < fiender.length; i++) {
ctx.fillStyle = "blue";
ctx.beginPath();
ctx.arc(fiender[i].x, fiender[i].y, fiender[i].r, 2*Math.PI, 0);
ctx.closePath();
ctx.fill();
fiender[i].y += fiender[i].vy;
if (fiender.y >= canvas.height) {
circles.splice(i,1)
};
}
requestAnimationFrame(bounceCircle);
}
setInterval(function(){
fiender.push({r: 5, x: Math.floor((Math.random() * 300) + 1), y: 0, vx:0 , vy: 3, f: "green"});
}, 800);
bounceCircle();
to see demo of what i have so far click the link DEMO
thanks
tast() in your version can be called whenever the player presses a key. At that time, the variable i within that function doesn't appear to point to your for loop variable. Execution might not be within that loop at the time tast() is called. You're also redefining the function with every call to bounceCircle(). Probably not good for performance, and not clearly necessary. A switch also makes more sense than the if statements currently used for key presses.
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d"),
farge = ["blue", "darkorchid", "yellowgreen", "violet", "peru", "darkorange",
"lightskyblue"],
tileldig = Math.floor((Math.random() * 300) + 1);
var kuler = [
{r: 10, x: canvas.width/2, y: canvas.height-100, f: "red"},
//{r: 50, x: tileldig, y: 50, vx:0 , vy: 3, f: "green"},
];
var fiender = [
{r: 5, x: tileldig, y: 50, vx:0 , vy: 3, },
];
document.onkeydown = function tast (e) {
switch (e.keyCode) {
case 37:
kuler[0].x -= 10;
break;
case 39:
kuler[0].x += 10;
break;
case 38:
kuler[0].y -= 10;
break;
case 40:
kuler[0].y += 10;
break;
}
};
function bounceCircle () {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < kuler.length; i++) {
kuler[i].x += 0;
kuler[i].y += 0;
ctx.fillStyle = kuler[i].f;
ctx.beginPath();
ctx.arc(kuler[i].x, kuler[i].y, kuler[i].r, 2*Math.PI, 0);
ctx.closePath();
ctx.fill();
}
for (var i = 0; i < fiender.length; i++) {
ctx.fillStyle = "blue";
ctx.beginPath();
ctx.arc(fiender[i].x, fiender[i].y, fiender[i].r, 2*Math.PI, 0);
ctx.closePath();
ctx.fill();
fiender[i].y += fiender[i].vy;
if (fiender.y >= canvas.height) {
circles.splice(i,1)
}
}
requestAnimationFrame(bounceCircle);
}
setInterval(function(){
fiender.push({r: 5, x: Math.floor((Math.random() * 300) + 1), y: 0, vx:0 ,
vy: 3, f: "green"});
}, 800);
bounceCircle();
This works (fiddle), although it no longer loops through multiple "kuler"s. It's not clear to me why you need more than one given the example, but this should get you moving in the right direction.

Changing speed for each shape on canvas

How change the speed of each shape?
I tried to play with pct but I guess this is wrong way:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
window.requestAnimFrame = (function (callback) {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
// shape stuff
var shapes = [];
var points;
// shape#1
points = pointsToSingleArray([{
x: 20,
y: 20
}, {
x: 50,
y: 100
}, {
x: 75,
y: 20
}, {
x: 100,
y: 100
}]);
shapes.push({
width: 20,
height: 10,
waypoints: points,
color: "red"
});
// shape#2
points = pointsToSingleArray([{
x: 0,
y: 0
}, {
x: 180,
y: 0
}, {
x: 180,
y: 180
}, {
x: 0,
y: 180
}, {
x: 0,
y: 0
}, {
x: 100,
y: 80
}]);
shapes.push({
width: 20,
height: 20,
waypoints: points,
color: "blue"
});
// animation stuff
var index = 0;
var fps = 60;
// start animating
animate();
function pointsToSingleArray(points) {
// array to hold all points on this polyline
var allPoints = [];
// analyze all lines formed by this points array
for (var a = 1; a < points.length; a++) { // loop through each array in points[]
// vars for interpolating steps along a line
var dx = points[a].x - points[a - 1].x;
var dy = points[a].y - points[a - 1].y;
var startX = points[a - 1].x;
var startY = points[a - 1].y;
// calc 100 steps along this particular line segment
for (var i = 1; i <= 100; i++) {
var pct = Math.min(1, i * .01);
var nextX = startX + dx * pct;
var nextY = startY + dy * pct;
allPoints.push({
x: nextX,
y: nextY
});
}
}
return (allPoints);
}
function animate() {
setTimeout(function () {
// this flag becomes true if we made any moves
// If true, we later request another animation frame
var weMoved = false;
// clear the canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// draw all shapes
for (var i = 0; i < shapes.length; i++) {
// get reference to next shape
var shape = shapes[i];
// check if we still have waypoint steps for this shape
if (index < shape.waypoints.length) {
// we're not done, so set the weMoved flag
weMoved = true;
// draw this shape at its next XY
drawShape(shape, index);
} else {
// we're done animating this shape
// draw it in its final position
drawShape(shape, shape.waypoints.length - 1);
}
}
// goto next index XY in the waypoints array
// Note: incrementing by 2 doubles animation speed
index += 2;
// if weMoved this frame, request another animation loop
if (weMoved) {
requestAnimFrame(animate)
};
}, 1000 / fps);
}
function drawShape(shape, waypointIndex) {
var x = shape.waypoints[waypointIndex].x;
var y = shape.waypoints[waypointIndex].y;
ctx.fillStyle = shape.color;
ctx.fillRect(x, y, shape.width, shape.height);
}
Maybe somebody know examples with changing speed, or how to make the code better.
http://jsfiddle.net/4DxLL/ - changing speed
var index = [0, 0];
shapes.push({
width: 20,
height: 10,
waypoints: points,
color: "red",
speed: 10,
});
index[i] += shape.speed;

Categories