Speed up Starfield Canvas animation and control it - javascript

Im trying to create a canvas animation of starfield. It has a fixed speed value so stars moving in same speeds but now I want to start it with stars not moving and when you click a button i want to start it slowly and then gradually increase the speed and then again slow down and stop. How do I achieve this?
Speeds should be like this example
https://www.shadertoy.com/view/Xdl3D2
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<canvas id="c" width="900px" height="700px"></canvas>
<script type="text/javascript">
const canvas = document.getElementById('c');
const c = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
window.addEventListener('wheel', (event) => {
if (event.deltaY < 0) speed *= 1.1;
else speed *= 0.9;
if (speed < 0.01) speed = 0.01;
else if (speed > 0.1) speed = 0.1;
});
class Star {
constructor() {
this.x = Math.random()*canvas.width-canvas.width/2;
this.y = Math.random()*canvas.height-canvas.height/2;
this.px, this.py;
this.z = Math.random()*4;
}
update() {
this.px = this.x;
this.py = this.y;
this.z += speed;
this.x += this.x*(speed*0.2)*this.z;
this.y += this.y*(speed*0.2)*this.z;
if (this.x > canvas.width/2+50 || this.x < -canvas.width/2-50 ||
this.y > canvas.height/2+50 || this.y < -canvas.height/2-50) {
this.x = Math.random()*canvas.width-canvas.width/2;
this.y = Math.random()*canvas.height-canvas.height/2;
this.px = this.x;
this.py = this.y;
this.z = 0;
}
}
show() {
c.lineWidth = this.z;
c.beginPath();
c.moveTo(this.x, this.y);
c.lineTo(this.px, this.py);
c.stroke();
}
}
let speed = 0.09;
let stars = [];
for (let i = 0; i < 1000; i++) stars.push(new Star());
c.fillStyle = 'rgba(0, 0, 0, 0.4)';
c.strokeStyle = 'rgb(255, 255, 255, 0.5)';
c.translate(canvas.width/2, canvas.height/2);
function draw() {
requestAnimationFrame(draw);
c.fillRect(-canvas.width/2, -canvas.height/2, canvas.width, canvas.height);
for (let s of stars) {
s.update();
s.show();
}
}
draw();
</script>
<style type="text/css">
body {
padding: 0;
margin: 0;
}
canvas {
position: absolute;
width: 100%;
height: 100%;
}
</style>
</body>
</html>

You have to increase the speed in the function draw to create a speeding up effect, and decrease to slowdown.
const canvas = document.getElementById('c');
const c = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
class Star {
constructor() {
this.x = Math.random() * canvas.width - canvas.width / 2;
this.y = Math.random() * canvas.height - canvas.height / 2;
this.px, this.py;
this.z = Math.random() * 4;
}
update() {
this.px = this.x;
this.py = this.y;
this.z += speed;
this.x += this.x * (speed * 0.2) * this.z;
this.y += this.y * (speed * 0.2) * this.z;
if (this.x > canvas.width / 2 + 50 || this.x < -canvas.width / 2 - 50 ||
this.y > canvas.height / 2 + 50 || this.y < -canvas.height / 2 - 50) {
this.x = Math.random() * canvas.width - canvas.width / 2;
this.y = Math.random() * canvas.height - canvas.height / 2;
this.px = this.x;
this.py = this.y;
this.z = 0;
}
}
show() {
c.lineWidth = this.z;
c.beginPath();
c.moveTo(this.x, this.y);
c.lineTo(this.px, this.py);
c.stroke();
}
}
let speed = 0.005;
let speed_inc = 0.0002;
let stars = [];
for (let i = 0; i < 1000; i++) stars.push(new Star());
c.fillStyle = 'rgba(0, 0, 0, 0.4)';
c.strokeStyle = 'rgb(255, 255, 255, 1)';
c.translate(canvas.width / 2, canvas.height / 2);
function draw() {
requestAnimationFrame(draw);
c.fillRect(-canvas.width / 2, -canvas.height / 2, canvas.width, canvas.height);
for (let s of stars) {
s.update();
s.show();
}
if (speed >= 0.005) {
speed += speed_inc
if (speed > 0.1)
speed_inc = -0.0004;
}
}
draw();
body {
padding: 0;
margin: 0;
}
canvas {
position: absolute;
width: 100%;
height: 100%;
}
<canvas id="c" width="900px" height="700px"></canvas>

Related

Create a "tail" for an object that is orbiting

Edit
Here is a JSFiddle with the code for the "tail" function commenting out.Solar System JSFiddle
I have this object I am working on that has an object orbiting a center mass. That works perfectly.
I am now trying to add a trailing line or "tail" that follows behind the planet.
My tail object looks like this:
function Tail(maxLength){
this.points = [];
this.maxLength = maxLength;
this.addPoint = function(point){
for(var i = Math.min(maxLength, this.points.length); i < maxLength; i++){
this.points[i] = this.points[i - 1];
}
this.points[0] = point;
}
this.draw = function(ctx){
for(var i = 1; Math.min(maxLength, this.points.length); i++){
if(i < maxLength - 20){
ctx.globalAlpha = 1;
} else {
ctx.globalAlpha = (this.maxLength - i) / 20;
}
ctx.beginPath();
ctx.moveTo(this.points[i - 1].x, this.points[i - 1].y);
ctx.lineTo(this.points[i].x, this.points[i].y);
ctx.stroke();
}
ctx.globalAlpha = 1;
}
}
The addPoint function takes an object that looks like '{x: currentX, y: currentY}
currentX and currentY are the x and y point of the object when ever it gets called.
I am lost on how I need to add the point to the points array and then draw based on those coordinates.
I modified your version to working condition
var canvas, width, height, ctx;
var bodies = [];
function init(){
canvas = document.getElementById("space-time");
width = window.innerWidth;
height = window.innerHeight;
canvas.width = width;
canvas.height = height;
ctx = canvas.getContext('2d');
createBodies();
setInterval(function(){
updateSystem();
updateBodies(0.01);
ctx.clearRect(0, 0, width, height);
drawBodies();
}, 10);
}
function createBodies(){
bodies.push(new Body((this.width / 2) - 250, (this.height / 2) - 300, 200, 0, 1, 10, "#14c71d", true));
bodies.push(new Body((this.width / 2) + 100, (this.height / 2) + 100, 350, 0, 1, 5, "#de2d16", true));
bodies.push(new Body(this.width / 2, this.height / 2, 0, 0, 1000000, 30, "#FF8501", false)); //sun
}
function drawBodies(){
for(var i = 0; i < bodies.length; i++){
bodies[i].draw(ctx);
}
}
function updateBodies(dt){
for(var i = 0; i < bodies.length; i++){
bodies[i].update(dt);
}
}
function updateSystem(){
var G = 10;
for(var i = 0; i < bodies.length; i++){
for(var j = 0; j < bodies.length; j++){
if(i === j) continue;
var b1 = bodies[i];
var b2 = bodies[j];
var dist = Math.sqrt((b1.x - b2.x) * (b1.x - b2.x) + (b1.y - b2.y) * (b1.y - b2.y));
var force = G * (b1.m * b2.m) / dist / dist;
var nx = (b2.x - b1.x) / dist;
var ny = (b2.y - b1.y) / dist;
b1.ax += nx * force / b1.m;
b1.ay += ny * force / b1.m;
b2.ax -= nx * force / b2.m;
b2.ay -= ny * force / b2.m;
}
}
}
function Body(x, y, v, angle, mass, radius, color, hasTail){
this.x = x;
this.y = y;
this.vx = v * Math.cos(angle);
this.vy = v * Math.sin(angle);
this.m = mass;
this.radius = radius;
this.color = color;
this.ax = 0;
this.ay = 0;
if (hasTail) {
this.tail = new Tail(50);
}
this.update = function(dt){
this.vx += this.ax * dt;
this.vy += this.ay * dt;
this.x += this.vx * dt;
this.y += this.vy * dt;
this.ax = 0;
this.ay = 0;
if(this.tail){
this.tail.addPoint({x: this.x, y: this.y});
}
}
this.draw = function(ctx){
ctx.strokeStyle = this.color;
ctx.fillStyle = this.color;
ctx.shadowColor = this.color;
ctx.shadowBlur = 5;
if(this.tail){
this.tail.draw(ctx);
}
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, 6.28);
ctx.fill();
}
}
function Tail(maxLength){
this.points = [];
this.maxLength = maxLength;
this.addPoint = point => {
this.points = [point].concat(this.points).slice(0, this.maxLength);
}
this.draw = function(ctx){
for(var i = 1; i < this.points.length; i++){
ctx.beginPath();
if(i < maxLength - 20){
ctx.globalAlpha = 1;
} else {
ctx.globalAlpha = (this.maxLength - i) / 20;
}
ctx.moveTo(this.points[i - 1].x, this.points[i - 1].y);
ctx.lineTo(this.points[i].x, this.points[i].y);
ctx.stroke();
}
ctx.globalAlpha = 1;
}
}
#space-time {
background-color: #1a1a1c;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Solar System AJ</title>
</head>
<body onload="init();">
<canvas id="space-time"></canvas>
</body>
</html>
You can visualisate the track of objects, if you fill frame with background with low opacity instead of clearing it:
var canvas, width, height, ctx;
var bodies = [];
function init(){
canvas = document.getElementById("space-time");
width = window.innerWidth;
height = window.innerHeight;
canvas.width = width;
canvas.height = height;
ctx = canvas.getContext('2d');
createBodies();
setInterval(function(){
updateSystem();
updateBodies(0.01);
// ctx.clearRect(0, 0, width, height);
// All magic here:
ctx.fillStyle = `rgba(0, 0, 0, .05)`;
ctx.shadowBlur = 0;
ctx.fillRect(0, 0, canvas.width, canvas.height);
drawBodies();
}, 10);
}
function createBodies(){
bodies.push(new Body((this.width / 2) - 250, (this.height / 2) - 300, 200, 0, 1, 10, "#14c71d", true));
bodies.push(new Body((this.width / 2) + 100, (this.height / 2) + 100, 350, 0, 1, 5, "#de2d16", true));
bodies.push(new Body(this.width / 2, this.height / 2, 0, 0, 1000000, 30, "#FF8501", false)); //sun
}
function drawBodies(){
for(var i = 0; i < bodies.length; i++){
bodies[i].draw(ctx);
}
}
function updateBodies(dt){
for(var i = 0; i < bodies.length; i++){
bodies[i].update(dt);
}
}
function updateSystem(){
var G = 10;
for(var i = 0; i < bodies.length; i++){
for(var j = 0; j < bodies.length; j++){
if(i === j) continue;
var b1 = bodies[i];
var b2 = bodies[j];
var dist = Math.sqrt((b1.x - b2.x) * (b1.x - b2.x) + (b1.y - b2.y) * (b1.y - b2.y));
var force = G * (b1.m * b2.m) / dist / dist;
var nx = (b2.x - b1.x) / dist;
var ny = (b2.y - b1.y) / dist;
b1.ax += nx * force / b1.m;
b1.ay += ny * force / b1.m;
b2.ax -= nx * force / b2.m;
b2.ay -= ny * force / b2.m;
}
}
}
function Body(x, y, v, angle, mass, radius, color, hasTail){
this.x = x;
this.y = y;
this.vx = v * Math.cos(angle);
this.vy = v * Math.sin(angle);
this.m = mass;
this.radius = radius;
this.color = color;
this.ax = 0;
this.ay = 0;
this.update = function(dt){
this.vx += this.ax * dt;
this.vy += this.ay * dt;
this.x += this.vx * dt;
this.y += this.vy * dt;
this.ax = 0;
this.ay = 0;
}
this.draw = function(ctx){
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, 6.28);
ctx.strokeStyle = this.color;
ctx.fillStyle = this.color;
ctx.shadowColor = this.color;
ctx.shadowBlur = 5;
ctx.fill();
}
}
#space-time {
background-color: #1a1a1c;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Solar System AJ</title>
</head>
<body onload="init();">
<canvas id="space-time"></canvas>
</body>
</html>

HTML 5 Canvas - making ball bounce on click & c.fill doesn't work?

I'm trying to make a ball which moves on a line and it bounces on it when clicked on it, but I don't know how to make it bounce on click.
Also, c.fill() doesn't work, I don't know why. (I've used it to fill the ball, maybe it doesn't work like that?)
Any advice would be really helpful since I'm a beginner in canvas, but know these 2 problems really concern me as I can't find any solutions for any of them. 😞
document.addEventListener('DOMContentLoaded', function () {
var canvas = document.querySelector('canvas');
var canvasx = document.getElementById('hr');
var c = canvas.getContext('2d');
canvas.width = canvasx.clientWidth;
canvas.height = canvasx.clientHeight;
var x = 80;
var y = 30;
var dx = 6;
var dy = 2;
var radius = 15;
var gravity = Math.random();
var friction = 0.9;
function animate() {
requestAnimationFrame(animate);
c.clearRect(0, 0, canvas.width, canvas.height);
c.beginPath();
c.arc(x, y, radius, 0, Math.PI * 2, false);
c.strokeStyle = "#eeede7";
c.stroke();
c.beginPath();
c.moveTo(50, canvas.height);
c.lineTo(1870, canvas.height);
c.lineWidth = 3;
c.fillStyle = "#77dff1";
c.fill();
c.strokeStyle = "#77dff1";
c.stroke();
update = function () {
if (y + 20 > canvas.height) {
dy = -dy * friction;
}
else {
dy += gravity;
}
y += dy;
x += dx;
}
function bounce() {
if ((x + radius + 50) > canvas.width || (x - radius - 50) < 0) {
dx = -dx;
}
}
update();
bounce();
}
animate();
function over() {
var px = event.pageX;
if (x - px < 0 || x - px > 0)
{
dx = -dx;
}
}
function bounceBall()
{
}
canvas.addEventListener('mouseover', over, false);
canvas.addEventListener('click', bounceBall, false)
}, false);
#hr {
position: relative;
bottom: 5%;
width: 100%;
margin: 0 auto;
}
hr {
border-color: #77dff1;
max-width: 90%;
}
canvas {
width: 100%;
}
<div id="hr">
<canvas></canvas>
<script src="js/canvas.js"></script>
</div>

Creating Objects Through Arays

I'm trying to make 2 rows and 5 columns of bricks using an object, but It doesn't seem to be working. I tried looking it up and using arrays, but It still didn't seem to work.
The bricks have a class of Brick
Demo
Here's the JavaScript
let canvas = $("#canvas")[0];
let ctx = canvas.getContext("2d");
let mouseX = 0;
let mouseY = 0;
class Paddle {
constructor(x, y, w, h, color) {
this.x = canvas.width / 2 - 100 / 2;
this.y = canvas.height - 60;
this.w = 100;
this.h = 10;
this.color = "#fff";
}
draw() {
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.w, this.h);
}
}
class Ball {
constructor (x, y, r, speedX, speedY, color) {
this.x = canvas.width / 2 - 10 / 2;
this.y = canvas.height / 2 - 10 / 2;
this.r = 10;
this.speedX = 3;
this.speedY = 3;
this.color = "#fff";
}
draw() {
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2);
ctx.fill();
}
animate() {
this.x += this.speedX;
this.y += this.speedY;
}
collision() {
if(this.x >= canvas.width) {
this.speedX *= -1;
}
if(this.x <= 0) {
this.speedX *= -1;
}
if(this.y >= canvas.height) {
this.reset();
}
if(this.y <= 0) {
this.speedY *= -1;
}
let paddleTop = paddle.y;
let paddleBottom = paddleTop + paddle.h;
let paddleLeft = paddle.x;
let paddleRight = paddle.x + paddle.w;
if(ball.x >= paddleLeft &&
ball.x <= paddleRight &&
ball.y >= paddleTop &&
ball.y <= paddleBottom) {
ball.speedY *= -1;
ballControl();
}
}
reset() {
this.speedX = 3;
this.speedY = 3;
this.x = canvas.width / 2 - 10 / 2;
this.y = canvas.height / 2 - 10 / 2;
}
}
class Brick {
constructor(x, y, w, h, col, row, gap, color) {
this.x = 0;
this.y = 0;
this.w = 100;
this.h = 50;
this.col = 5; //# of brick columns
this.row = 2; //# of brick rows
this.gap = 2; //gap betweeb each brick
this.color = "#0000ff";
}
draw() {
for(let brickRow = 0; brickRow < this.row; brickRow++) {
for(let brickCol = 0; brickCol < this.col; brickCol++) {
ctx.fillStyle = this.color;
ctx.fillRect(this.x * brickCol, this.y * brickRow, this.w - this.gap, this.h - this.gap);
}
}
}
}
let paddle = new Paddle(this.x, this.y, this.w, this.h, this.color);
let ball = new Ball(this.x, this.y, this.r, this.speedX, this.speedY, this.color);
let brick = new Brick(this.x, this.y, this.w, this.h, this.col, this.row, this.gap, this.color);
// START
$(document).ready(() => {
let fps = 120;
setInterval(init, 1000 / fps);
$(canvas).bind("mousemove", paddleControl);
})
// INIT
let init = () => {
draw();
animate();
collision();
}
// DRAW
let draw = () => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
paddle.draw();
ball.draw();
brick.draw();
}
// ANIMATE
let animate = () => {
ball.animate();
}
// COLLISION
let collision = () => {
ball.collision();
}
// BALL CONTROL
let ballControl = () => {
let paddleCenter = paddle.x + paddle.w / 2;
let ballDistFromPaddleCenter = ball.x - paddleCenter;
ball.speedX = ballDistFromPaddleCenter * 0.15;
}
// PADDLE CONTROL
let paddleControl = (e) => {
let rect = canvas.getBoundingClientRect();
let root = document.documentElement;
mouseX = e.pageX - rect.left - root.scrollLeft;
mouseY = e.pageY - rect.top - root.scrollTop;
paddle.x = mouseX;
}
"Doesn't seem to work" is insufficient when describing your problem. You need to say what you expect and what you observe. Failing to do so has attracted 2 close votes for the reason that the question is unclear.
One of your problems is the way that you calculate the position of each brick.
Another potential problem is that you have one object representing all bricks, a better way would be for each brick to be it's own object - this will simplify collision detection (a lot!)
Your code also relies upon the script element appearing after all of the HTML - while functional, this is a broken paradigm. While it is good practise to put it after the html, so that the content is first rendered as soon as possible, having code that only works when it's put there is not so good. For instance - the classes wont initialise before the canvas has been located (since they rely on it's width - a better option would be to have them rely on a separate width variable, which is set to the width of the canvas during page init)
Couldn't get the fiddle to work, nor a snippet for that matter. But here's your code reworked a little. I can now see 2 rows of 5 blue bricks.
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<style>
#canvas {
position: absolute;
background-color: #000;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
}
</style>
<head>
<body>
<canvas id="canvas" width="600" height="500"></canvas>
<script>
var canvas, ctx, mouseX=0, mouseY=0;
canvas = $("#canvas")[0];
ctx = canvas.getContext("2d");
mouseX = 0;
mouseY = 0;
class Paddle
{
constructor(x, y, w, h, color)
{
this.x = canvas.width / 2 - 100 / 2;
this.y = canvas.height - 60;
this.w = 100;
this.h = 10;
this.color = "#fff";
}
draw()
{
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.w, this.h);
}
}
class Ball {
constructor (x, y, r, speedX, speedY, color) {
this.x = canvas.width / 2 - 10 / 2;
this.y = canvas.height / 2 - 10 / 2;
this.r = 10;
this.speedX = 3;
this.speedY = 3;
this.color = "#fff";
}
draw() {
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2);
ctx.fill();
}
animate() {
this.x += this.speedX;
this.y += this.speedY;
}
collision() {
if(this.x >= canvas.width) {
this.speedX *= -1;
}
if(this.x <= 0) {
this.speedX *= -1;
}
if(this.y >= canvas.height) {
this.reset();
}
if(this.y <= 0) {
this.speedY *= -1;
}
let paddleTop = paddle.y;
let paddleBottom = paddleTop + paddle.h;
let paddleLeft = paddle.x;
let paddleRight = paddle.x + paddle.w;
if(ball.x >= paddleLeft &&
ball.x <= paddleRight &&
ball.y >= paddleTop &&
ball.y <= paddleBottom) {
ball.speedY *= -1;
ballControl();
}
}
reset() {
this.speedX = 3;
this.speedY = 3;
this.x = canvas.width / 2 - 10 / 2;
this.y = canvas.height / 2 - 10 / 2;
}
}
class Brick {
constructor(x, y, w, h, col, row, gap, color) {
this.x = 0;
this.y = 0;
this.w = 100;
this.h = 50;
this.col = 5; //# of brick columns
this.row = 2; //# of brick rows
this.gap = 2; //gap betweeb each brick
this.color = "#0000ff";
}
draw() {
for(let brickRow = 0; brickRow < this.row; brickRow++)
{
for(let brickCol = 0; brickCol < this.col; brickCol++)
{
ctx.fillStyle = this.color;
ctx.fillRect( (this.w+this.gap) * brickCol, (this.h+this.gap) * brickRow, this.w, this.h );
}
}
}
}
let paddle = new Paddle(this.x, this.y, this.w, this.h, this.color);
let ball = new Ball(this.x, this.y, this.r, this.speedX, this.speedY, this.color);
let brick = new Brick(this.x, this.y, this.w, this.h, this.col, this.row, this.gap, this.color);
// START
$(document).ready(() => {
let fps = 120;
setInterval(init, 1000 / fps);
$(canvas).bind("mousemove", paddleControl);
})
// INIT
let init = () => {
draw();
animate();
collision();
}
// DRAW
let draw = () => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
paddle.draw();
ball.draw();
brick.draw();
}
// ANIMATE
let animate = () => {
ball.animate();
}
// COLLISION
let collision = () => {
ball.collision();
}
// BALL CONTROL
let ballControl = () => {
let paddleCenter = paddle.x + paddle.w / 2;
let ballDistFromPaddleCenter = ball.x - paddleCenter;
ball.speedX = ballDistFromPaddleCenter * 0.15;
}
// PADDLE CONTROL
let paddleControl = (e) => {
let rect = canvas.getBoundingClientRect();
let root = document.documentElement;
mouseX = e.pageX - rect.left - root.scrollLeft;
mouseY = e.pageY - rect.top - root.scrollTop;
paddle.x = mouseX;
}
</script>
</body>
</html>

How to make canvas particles follow mouse with JS?

I want to make the particles follow the mouse and I am not sure on how to do that.
I figured I can replace the x and y with the mouses position but I can figure that out either.
I would appreciate an almost exact answer and not examples please.
window.onload = function() {
var canvas = document.createElement("canvas"),
c = canvas.getContext("2d"),
particles = {}
particleIndex = 0,
particleNum = Math.random() * 2;
canvas.width = 400;
canvas.height = 400;
document.body.appendChild(canvas);
c.fillStyle = "black";
c.fillRect(0, 0, canvas.width, canvas.height);
function Particle() {
this.x = canvas.width / 10;
this.y = canvas.height / 2;
this.vx = Math.random() * 10 - 5;
this.vy = Math.random() * 10 - 5;
this.gravity = .2;
particleIndex++;
particles[particleIndex] = this;
this.id = particleIndex;
this.life = 0;
this.maxLife = Math.random() * 30 + 10;
this.color = "rgb(" + parseInt(Math.random() * 255, 10) + ",0,0)";
this.color2 = "hsl(" + parseInt(Math.random() * 255, 10) + ",50%,50%)";
}
Particle.prototype.draw = function() {
this.x += this.vx;
this.y += this.vy;
if (Math.random() < 0.1) {
this.vx = Math.random() * 10 - 5;
this.vy = Math.random() * 10 - 5;
}
this.vy += this.gravity;
this.life++;
if (this.Life >= this.maxLife) {
delete particles[this.id];
}
c.fillStyle = this.color2;
c.fillRect(this.x, this.y, 10, 10);
};
//var p = new Particle();
setInterval(function() {
c.fillStyle = "rgba(0,0,0,0.5)";
c.fillRect(0, 0, canvas.width, canvas.height);
for (var i in particles) {
particles[i].draw();
}
for (var i = 0; i < particleNum; i++) {
new Particle();
}
}, 30);
};

Animate objects on canvas with an array

Been trying to animate an object on canvas by putting it in an array but it wont seem to work.
Only have one object drawn at the moment but the thought is to add several more objects to the canvas hence the array.
Is there something wrong with the functions im using to draw and animate the object?
var draw;
function Canvas(canvas, ctx) {
this.canvas = canvas;
this.ctx = ctx;
}
function Direction(x, y) {
this.x = x;
this.y = y;
}
function Measures(cW, cH, radius, hR, degree, dirX, dirY, degree) {
this.cW = cW;
this.cH = cH;
this.radius = radius;
this.hR = hR;
this.dirX = dirX;
this.dirY = dirY;
this.degree = degree;
}
function Drawing(cW, cH, width, height, radius, hR, color) {
this.cW = canvas.width;
this.cH = canvas.height;
this.width = width;
this.height = height;
this.radius = height / 2;
this.hR = width - this.radius;
this.color = color;
this.render = function() {
ctx.fillStyle = this.color;
ctx.strokeStyle = this.color;
ctx.lineWidth = 1;
ctx.save();
ctx.translate(this.x, this.y);
ctx.rotate(this.degree * Math.PI / 180);
ctx.translate(-this.x, -this.y);
ctx.beginPath();
ctx.moveTo(this.x, this.y);
ctx.lineTo(x + this.hR, this.y);
ctx.arc(this.x + this.hR, this.y + this.radius, this.radius, - Math.PI / 2, Math.PI / 2);
ctx.lineTo(this.x, this.y + height);
ctx.closePath();
ctx.fill();
ctx.stroke();
ctx.restore();
}
this.move = function(multiplier) {
var multiplier = 2;
var borders = 5;
if(this.dirX > 0 && this.x > this.cW - borders - width){
this.degree = 90;
this.dirX = 0;
this.dirY = 1;
this.x = cW - borders;
}
else if(this.dirY > 0 && this.y > this.cH - borders - width){
this.degree = 180;
this.dirX = -1;
this.dirY = 0;
this.y = this.cH - borders;
}
else if(this.dirX < 0 && this.x < borders + width){
this.degree = -90;
this.dirX = 0;
this.dirY = -1;
this.x = borders;
}
else if(this.dirY < 0 && this.y < borders + width){
this.degree = 0;
this.dirX = 1;
this.dirY = 0;
this.y = borders;
}
this.x += this.dirX * multiplier;
this.y += this.dirY * multiplier;
this.render();
}
}
function animate() {
ctx.clearRect(0, 0, this.cW, this.cH);
draw.forEach(function(object) {
object.render(2);
});
requestAnimationFrame(animate);
}
function init() {
this.canvas = document.getElementById("my_canvas");
this.ctx = canvas.getContext("2d");
this.degree = Math.PI / 2;
draw = [];
draw.push(new Drawing(5, 5, 80, 60, new Direction(1,0), "#E5E5E5"));
animate();
}
window.onload = init;
</script>
<canvas id="my_canvas" width="1000" height="800" style="background-color:#33CC33"></canvas>

Categories

Resources