setInterval is slowing down over time [duplicate] - javascript

This question already has an answer here:
HTML5 Canvas slows down with each stroke and clear
(1 answer)
Closed 4 years ago.
I've just started learning javascript.
My problem is, that the website is slowing down after a few seconds. I'm using setinterval to "tick" the things on the screen and i feel like this might be the cause of the problem.
Here is my code:
var r = [];
var ctx;
function init() {
ctx = document.getElementById("canvas").getContext("2d");
for(var i = 0; i < 20; i++) {
var x = Math.floor(Math.random() * (ctx.canvas.width - 20)) + 10;
var y = Math.floor(Math.random() * (ctx.canvas.height - 20)) + 10;
r.push(new Rect(x,y, 10, 10, ctx));
}
window.setInterval(tick,10);
window.setInterval(draw,10);
}
function tick() {
for(var i = 0; i < r.length; i++) {
r[i].tick();
}
}
function draw() {
ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height);
for(var i = 0; i < r.length; i++) {
r[i].draw();
}
ctx.lineWidth = 5;
ctx.rect(0,0,ctx.canvas.width,ctx.canvas.height);
ctx.stroke();
}
Here's another class:
class Rect {
constructor(x, y, width, height, ctx) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.cxt = ctx;
this.xVel = 2.5;
this.yVel = 2.5;
if (Math.random() < 0.5) {
this.xVel = -this.xVel;
}
if (Math.random() < 0.5) {
this.yVel = -this.yVel;
}
}
tick(){
this.x += this.xVel;
this.y += this.yVel;
if (this.x + this.width >= ctx.canvas.width | this.x <= 0){
this.xVel = -this.xVel;
}
if (this.y + this.height >= ctx.canvas.height | this.y <= 0){
this.yVel = -this.yVel;
}
}
draw() {
ctx.fillRect(this.x,this.y,this.width,this.height);
}
}
So what exactly is the cause of this issue and how can i fix it?
You can download the files here: https://drive.google.com/file/d/1pg4ASPvjbo2ua_7cCvQvzucLgbegtiw6/view?usp=sharing

This issue is in your draw function.
Canvas-es remember all the lines drawn, over time it slows down your animation.
The solution is to reset the lines drawn list by calling ctx.beginPath()
function draw() {
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
for (var i = 0; i < r.length; i++) {
r[i].draw();
}
ctx.beginPath()
ctx.lineWidth = 5;
ctx.rect(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.stroke();
}

First of all the screen only refreshes at a rate of 16 milliseconds (assuming 60 frames per second). So calling the two function at 10 milliseconds is a bit overkill. But in the modern browser, we now have a native support to do anything when the screen refreshes. Its called request animation frame: requestAnimationFrame(animationrDrawCallback).
You can read more about it here: https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame. Now back to your code, it can be refactored like this:
const r = [];
const ctx;
function init() {
ctx = document.getElementById("canvas").getContext("2d");
for(let i = 0; i < 20; i++) {
const x = Math.floor(Math.random() * (ctx.canvas.width - 20)) + 10;
const y = Math.floor(Math.random() * (ctx.canvas.height - 20)) + 10;
r.push(new Rect(x,y, 10, 10, ctx));
}
// start our animation
window.requestAnimationFrame(render);
}
function render() {
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
r.forEach((item) => {
item.trick();
item.draw();
})
ctx.beginPath();
ctx.lineWidth = 5;
ctx.rect(0,0,ctx.canvas.width,ctx.canvas.height);
ctx.stroke();
// this will be called at next screen refresh
window.requestAnimationFrame(render);
}
The BIGGEST BONUS of using requestAnimationFrame is that it will stop executing when the tab is no longer in focus. Big boost for smartphones. Hope this helps.

Related

Why does the page start to lag when drawing many elements on the canvas?

I'm creating a game, and I need to draw) some elements at the top of the <canvas>, but the more elements appear, the more lag the page itself. I found this example where a lot of circles appear, but everything works fine - JSFiddle. Can someone tell me how to optimize my case?
"use strict";
/*Determing canvas*/
window.onload = () => {
const canvas = document.getElementById("canvas"),
ctx = canvas.getContext('2d'),
endTitle = document.getElementById('gameover');
let spawnRate = 300,
lastspawn = -1;
class Wall {
/*Getting values*/
constructor(x, y, width, height, speed) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.speed = speed;
}
/*Draw rectangle*/
draw() {
ctx.beginPath();
ctx.fillStyle = "#000000";
ctx.fillRect(this.x, this.y, this.width, this.height)
}
}
/*Making walls*/
let walls = [];
/*Spawn walls endlessly*/
function spawnWalls() {
const wall_x = Math.floor(Math.random() * (canvas.width - 20)) + 10
const wall_y = 0
for (let i = 0; i < 200; i++) {
walls.push(new Wall(wall_x, wall_y, 10, 10, 10))
}
}
/*Update game*/
function refresh() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
let time = Date.now()
if (time > (lastspawn + spawnRate)) {
lastspawn = time;
spawnWalls();
spawnRate -= 10;
}
walls.forEach(wall => wall.draw())
for (let j of walls) {
j.y += j.speed;
j.draw();
};
};
let interval = setInterval(refresh, 50);
Walls is too big.
It looks like you're never removing old walls, so they are continuing to be drawn well after they have been removed from the canvas. In your Refresh function, check if the wall has passed the canvas size and if so, remove that from the walls array.
EDIT:
I've added your 'remove' code from the comment.
Another easy win is to stop using new Date() because of who knows what, probably time zones and localization, dates are very expensive to instantiate. However modern browsers offer a performance API, and that can tell you the time since page load, which seems to have a substantial improvement on your existing performance.
"use strict";
/*Determing canvas*/
window.onload = () => {
const canvas = document.getElementById("canvas"),
ctx = canvas.getContext('2d'),
endTitle = document.getElementById('gameover');
let spawnRate = 300,
lastspawn = -1;
endTitle.style.display = "none";
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
/*Classes*/
class Player {
/*Get player info*/
constructor(x, y, width, height, speed) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.speed = speed;
}
/*Draw player*/
draw() {
ctx.beginPath();
ctx.fillStyle = "#000000";
ctx.fillRect(this.x, this.y, this.width, this.height);
}
/*Move player*/
move() {
}
};
class Wall {
/*Getting values*/
constructor(x, y, width, height, speed) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.speed = speed;
}
/*Draw rectangle*/
draw() {
ctx.beginPath();
ctx.fillStyle = "#000000";
ctx.fillRect(this.x, this.y, this.width, this.height)
}
}
/*Defining players*/
let player_01 = new Player(20, 70, 20, 20, 10);
let player_02 = new Player(50, 500, 20, 20, 10);
let players = [];
players.push(player_01);
/*Making walls*/
let walls = [];
/*Spawn Walls for infinity*/
function spawnWalls() {
const wall_x = Math.floor(Math.random() * (canvas.width - 20)) + 10
const wall_y = 0
for (let i = 0; i < 200; i++) {
walls.push(new Wall(wall_x, wall_y, 10, 10, 10))
}
}
/*Update game*/
function refresh() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
let time = performance.now()
if (time > (lastspawn + spawnRate)) {
lastspawn = time;
spawnWalls();
spawnRate -= 10;
}
walls.forEach(wall => wall.draw())
outOfWindow()
for (let i of players) {
i.draw();
};
for (let j of walls) {
if (j.y > canvas.height) {
walls.shift(j)
}
j.y += j.speed;
j.draw();
if (player_01.height + player_01.y > j.y && j.height + j.y > player_01.y && player_01.width + player_01.x > j.x && j.width + j.x > player_01.x) {
clearInterval(interval);
endTitle.style.display = "flex";
};
};
};
let interval = setInterval(refresh, 50);
/*Move players on keypress*/
for (let i of players) {
window.addEventListener("keydown", (event) => {
let key = event.key.toLowerCase();
if (key == "w") i.y -= i.speed;
else if (key == "s") i.y += i.speed;
else if (key == "a") i.x -= i.speed;
else if (key == "d") i.x += i.speed;
})
}
/*Check if player out of the window*/
function outOfWindow() {
for (let i of players) {
if (i.x < 0) i.x = 0;
else if (i.x + i.width > canvas.width) i.x = canvas.width - i.width;
else if (i.y < 0) i.y = 0;
else if (i.y + i.height > canvas.height) i.y = canvas.height - i.height;
}
}
}
#gameover {
position: absolute;
width: 100%;
height: 100%;
justify-content: center;
align-items: center;
flex-direction: column;
background-color: rgba(0, 0, 0, .5);
}
<div id="gameover">
<h2>The Game Is Over</h2>
<button onclick="restart()">Try again!</button>
</div>
<canvas id="canvas"></canvas>

Creating a checkered board with pieces in HTML5 canvas

I am experimenting with canvas in HTML and JS and attempting to draw a canvas of a chess board with 16 pieces on each side of it. I was able to create the chess board but am stuck on how I would draw just specifically the 16 pieces on each side (The pieces can just be circles so just one side with 16 red circles, one side with 16 blue circles).
I don't know why this is so confusing to me, I know you probably just need a for loop stopping at the specific coordinates but to get different colored pieces on each side as well as stopping at certain part is giving me trouble.
I would just like assistance on where in my code would I be placing the chess pieces in. If you could just modify my current code and place comments on where you made the changes so I could see then that would be very appreciated.
Here is what I have so far to make the checkers board:
<canvas id="canvas" width="300" height="300"></canvas>
function drawCheckeredBackground(can, nRow, nCol) {
var ctx = can.getContext("2d");
var w = can.width;
var h = can.height;
nRow = nRow || 8;
nCol = nCol || 8;
w /= nCol;
h /= nRow;
for (var i = 0; i < nRow; ++i) {
for (var j = 0, col = nCol / 2; j < col; ++j) {
ctx.rect(2 * j * w + (i % 2 ? 0 : w), i * h, w, h);
}
}
ctx.fill();
}
var canvas = document.getElementById("canvas");
drawCheckeredBackground(canvas);
Here is how I want the chess board to look like, with 16 pieces on each side like so. I just quickly made this example in paint:
https://i.imgur.com/BvbxzSZ.png
This isn't the most beautiful solution possible, but it should offer some basic ideas and is adjustable using your step variable idea. Chances are, you'll need to refactor when going for actual pieces.
const drawBoard = (ctx, step) => {
for (let i = 0; i < 8; i++) {
for (let j = 0; j < 8; j++) {
ctx.fillStyle = (i + j) & 1 ? "black" : "white";
ctx.fillRect(j * step, i * step, step, step);
}
}
};
const drawPieces = (ctx, y, color, step) => {
ctx.fillStyle = color;
for (let i = y; i < 2 * step + y; i += step) {
for (let j = step / 2; j < 8 * step; j += step) {
ctx.beginPath();
ctx.arc(j, i - step / 2, step / 3, 0, Math.PI * 2);
ctx.fill();
}
}
};
const step = 60;
const c = document.createElement("canvas");
c.height = c.width = step * 8;
document.body.appendChild(c);
const ctx = c.getContext("2d");
drawBoard(ctx, step);
drawPieces(ctx, step, "red", step);
drawPieces(ctx, step * 7, "blue", step);
Play with it at JSFiddle.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style>
body {
background-color: black;
}
canvas {
display: block;
margin: auto;
border: solid 1px white;
border-radius: 10px;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script type="application/javascript">
// Self executing function
void function() {
// Turn on strict js rules for this scope
"use strict";
// Classes
function ChessPeice(x,y,radius) {
this.x = x || 0.0;
this.y = y || 0.0;
this.radius = radius || 1.0;
}
ChessPeice.prototype = {
tick: function() {
},
render: function(ctx) {
ctx.moveTo(
this.x + this.radius,
this.y
);
ctx.arc(
this.x,
this.y,
this.radius,
0.0,
2.0 * Math.PI,
false
);
}
};
// Constructor, when called with 'new' creates an object and puts it
// in the 'this' variable, new properties can then be added to it.
function Chessboard(width,height) {
this.boardWidth = width || 1;
this.boardHeight = height || 1;
this.tileWidth = this.boardWidth / this.H_TILE_COUNT;
this.tileHeight = this.boardHeight / this.V_TILE_COUNT;
this.whitePeices = [];
this.blackPeices = [];
for (var y = 0; y < 2; ++y) {
for (var x = 0; x < this.V_TILE_COUNT; ++x) {
this.whitePeices.push(
new ChessPeice(
x * this.tileWidth + (this.tileWidth >> 1),
y * this.tileHeight + (this.tileHeight >> 1),
this.CHESS_PIECE_RADIUS
)
);
this.blackPeices.push(
new ChessPeice(
x * this.tileWidth + (this.tileWidth >> 1),
(this.V_TILE_COUNT - 1 - y) * this.tileHeight + (this.tileHeight >> 1),
this.CHESS_PIECE_RADIUS
)
);
}
}
}
// Prototype object, all objects created with 'new Chessboard()'
// will share the properties in the prototype, use it for constant values
// & class functions
Chessboard.prototype = {
H_TILE_COUNT: 8, // How many white & black tiles per axis?
V_TILE_COUNT: 8,
EDGE_THICKNESS: 10.0,
EDGE_COLOUR: "#603E11FF",
WHITE_TILE_COLOUR: "#BBBBBBFF",
BLACK_TILE_COLOUR: "#555555FF",
CHESS_PIECE_RADIUS: 5.0,
WHITE_PIECE_COLOUR: "#EEEEEEFF",
BLACK_PIECE_COLOUR: "#333333FF",
tick: function() {
// You can add game logic here
},
render: function(ctx) {
// Draw white tiles
var x = 0;
var y = 0;
var totalTiles = this.H_TILE_COUNT * this.V_TILE_COUNT;
ctx.fillStyle = this.WHITE_TILE_COLOUR;
ctx.beginPath();
for (var i = 0; i < totalTiles; ++i) {
ctx.rect(
x * this.tileWidth,
y * this.tileHeight,
this.tileWidth,
this.tileHeight
);
x += 2;
if (x >= this.H_TILE_COUNT) {
x = this.H_TILE_COUNT - x + 1;
++y;
}
}
ctx.fill();
// Draw black tiles
x = 1;
y = 0;
ctx.fillStyle = this.BLACK_TILE_COLOUR;
ctx.beginPath();
for (var i = 0; i < totalTiles; ++i) {
ctx.rect(
x * this.tileWidth,
y * this.tileHeight,
this.tileWidth,
this.tileHeight
);
x += 2;
if (x >= this.H_TILE_COUNT) {
x = this.H_TILE_COUNT - x + 1;
++y;
}
}
ctx.fill();
// Draw edge
ctx.lineWidth = this.EDGE_THICKNESS >> 1;
ctx.strokeStyle = this.EDGE_COLOUR;
ctx.beginPath();
ctx.rect(0,0,this.boardWidth,this.boardHeight);
ctx.stroke();
// Draw white pieces
ctx.lineWidth = 2;
ctx.strokeStyle = "#000000FF";
ctx.fillStyle = this.WHITE_PIECE_COLOUR;
ctx.beginPath();
for (var i = 0; i < this.whitePeices.length; ++i) {
this.whitePeices[i].render(ctx);
}
ctx.fill();
ctx.stroke();
// Draw black pieces
ctx.lineWidth = 2;
ctx.strokeStyle = "#000000FF";
ctx.fillStyle = this.BLACK_PIECE_COLOUR;
ctx.beginPath();
for (var i = 0; i < this.blackPeices.length; ++i) {
this.blackPeices[i].render(ctx);
}
ctx.fill();
ctx.stroke();
}
};
// Variables
var canvasWidth = 160;
var canvasHeight = 160;
var canvas = null;
var ctx = null;
var board = null;
// Game Loop
function loop() {
// Tick (Update game logic)
board.tick();
// Render
ctx.fillStyle = "gray";
ctx.fillRect(0,0,canvasWidth,canvasHeight);
board.render(ctx);
//
requestAnimationFrame(loop);
}
// Entry Point (Runs when the page loads)
onload = function() {
canvas = document.getElementById("canvas");
canvas.width = canvasWidth;
canvas.height = canvasHeight;
ctx = canvas.getContext("2d");
board = new Chessboard(canvasWidth,canvasHeight);
loop();
}
}();
</script>
</body>
</html>

How do I reset the velocity variable of my object

How can I reset the velocity variable in my objects. I am making a canvas game, in which stars fall from the top of the Canvas. Problem is when I run the game in a setinterval() the velocity keeps getting greater and greater. What i want is the speed to stay the same unless i change it.
function Star(x, y, rad, velocity, fill){
this.x = Math.floor(Math.random() * 999);//this create a random number between 0 and 599 on the x axis
this.y = 0;
this.rad = Math.floor((Math.random() * 30) + 15);//this create a random number between 10 and 30 for the radius
this.velocity = 5;
this.fill = fill
this.draw = function(){
ctx.beginPath();
ctx.fillStyle = this.fill;
ctx.arc(this.x, this.y, this.rad, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();
this.y += this.velocity;
}
}
function createMultipleStars(){
for (var i = 0; i <= numOfStars; i++)
stars[i] = new Star(i * 50, 10, i, i, "rgba(255,215,0,0.6)");
}
//createMultipleStars();
function step() {
ctx.clearRect(0,0,canvas.width, canvas.height);
for (var i = 0; i<= numOfStars; i++)
stars[i].draw();
requestAnimationFrame(step);
}
spaceShip.drawSpaceShip();
var myVar = setInterval(function(){ init() }, 4000);
function init(){
createMultipleStars();
step();
}
Your frames per second were increasing with each interval. Every four seconds another step function is added to the animation frame. To fix this I added an fps counter and singleton pattern. With the singleton pattern you shouldn't break the requestAnimationFrame max 60 fps. Without it you will see that the fps increases. Technically it can't go above 60 but the step function runs multiple times in the same frame increasing the velocity each time and making the stars run faster.
var canvas = document.getElementById('can');
var ctx = canvas.getContext('2d');
var stars = [];
var numOfStars = 10;
function Star(x, y, rad, velocity, fill) {
this.x = Math.floor(Math.random() * 999); //this create a random number between 0 and 599 on the x axis
this.y = 0;
this.rad = Math.floor((Math.random() * 30) + 15); //this create a random number between 10 and 30 for the radius
this.velocity = 5;
this.fill = fill
this.draw = function() {
ctx.beginPath();
ctx.fillStyle = this.fill;
ctx.arc(this.x, this.y, this.rad, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();
this.y += this.velocity;
}
}
function createMultipleStars() {
for (var i = 0; i <= numOfStars; i++) {
stars[i] = new Star(i * 50, 10, i, i, "rgba(255,215,0,0.6)");
}
}
function fps() {
var now = (new Date()).getTime();
fps.frames++;
if ((now - fps.lastFps) >= 1000) {
fps.total = fps.frames;
fps.lastFps = now;
fps.frames = 0;
}
return fps.total;
}
fps.frames = 0;
fps.lastFps = (new Date()).getTime();
fps.total = 0;
// Step is a singleton. Only one instance can be created.
function Step() {
// comment out the line below to see what happens when not running
// singleton
if (Step.instance !== null) return Step.instance;
var self = this;
function frame() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i <= numOfStars; i++) {
stars[i].draw();
}
ctx.fillStyle = "red";
ctx.fillText("FPS: " + fps(), 10, 10);
requestAnimationFrame(frame);
}
frame();
Step.instance = this;
return this;
}
Step.instance = null;
//spaceShip.drawSpaceShip();
function init() {
var myVar = setInterval(function() {
createMultipleStars();
var step = new Step();
}, 4000);
createMultipleStars();
//
var step = new Step();
var step = new Step();
var step = new Step();
var step = new Step();
}
init();
#can {
border: 1px solid #FF0000;
}
<canvas id="can" width="400" height="200"></canvas>
Your issue is very simple : you are using both requestAnimationFrame and setInterval to drive the animation. More and more render loops get created and run at the same time, causing the issue
Separate the concerns :
have one render loop working for ever with RequestAnimationFrame
Have a setInterval-ed function inject some new stuff in your game.
So the only change you need to do is here :
var myVar = setInterval(createMultipleStars, 4000);

How to make the canvas background transparent

I am a newbie on using html5 canvas.
And I'd like to use canvas generate a smoke animation and place it on top of a cigarette image.
The follow code is a sample code of a smoke generator but i don't know how to make the background of the canvas transparent.
I have try different globalCompositeOperation but it seem that i go into a wrong direction.(I don't know much about canvas
I need some help.
Sorry for my poor English.
The following is my code.
And the link is the sample code i used.
http://codepen.io/CucuIonel/pen/hFJlr
function start_smoke( smoke_id ) {
var canvas = document.getElementById(smoke_id);
var w = canvas.width = 200,
h = canvas.height = 150;
var c = canvas.getContext('2d');
var img = new Image();
img.src = 'http://oi41.tinypic.com/4i2aso.jpg';
var position = {x: w / 2, y: h};
var particles = [];
var random = function (min, max) {
return Math.random() * (max - min) * min;
};
function Particle(x, y) {
this.x = x;
this.y = y;
this.velY = -2;
this.velX = (random(1, 10) - 5) / 10;
this.size = random(3, 5) / 10;
this.alpha = 0.3;
this.update = function () {
this.y += this.velY;
this.x += this.velX;
this.velY *= 0.99;
if (this.alpha < 0)
this.alpha = 0;
c.globalAlpha = this.alpha;
c.save();
c.translate(this.x, this.y);
c.scale(this.size, this.size);
c.drawImage(img, -img.width / 2, -img.height / 2);
c.restore();
this.alpha *= 0.96;
this.size += 0.02;//
};
}
var draw = function () {
var p = new Particle(position.x, position.y);
particles.push(p);
while (particles.length > 500) particles.shift();
c.globalAlpha = 1;
c.fillRect(0, 0, w, h);
for (var i = 0; i < particles.length; i++) {
particles[i].update();
}
};
setInterval(draw, 1000 / 20);
}
$(function(){
start_smoke("main_censer_smoke");
});
Canvas transparent by default.
But anyway this question could have a pretty easy solution, which not using globalAlpha, and not using a rgba() color. The simple, effective answer is:
context.clearRect(0,0,width,height);

Multiple setInterval in a HTML5 Canvas game

I'm trying to achieve multiple animations in a game that I am creating using Canvas (it is a simple ping-pong game). This is my first game and I am new to canvas but have created a few experiments before so I have a good knowledge about how canvas work.
First, take a look at the game here.
The problem is, when the ball hits the paddle, I want a burst of n particles at the point of contact but that doesn't came right. Even if I set the particles number to 1, they just keep coming from the point of contact and then hides automatically after some time.
Also, I want to have the burst on every collision but it occurs on first collision only. I am pasting the code here:
//Initialize canvas
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d"),
W = window.innerWidth,
H = window.innerHeight,
particles = [],
ball = {},
paddles = [2],
mouse = {},
points = 0,
fps = 60,
particlesCount = 50,
flag = 0,
particlePos = {};
canvas.addEventListener("mousemove", trackPosition, true);
//Set it's height and width to full screen
canvas.width = W;
canvas.height = H;
//Function to paint canvas
function paintCanvas() {
ctx.globalCompositeOperation = "source-over";
ctx.fillStyle = "black";
ctx.fillRect(0, 0, W, H);
}
//Create two paddles
function createPaddle(pos) {
//Height and width
this.h = 10;
this.w = 100;
this.x = W/2 - this.w/2;
this.y = (pos == "top") ? 0 : H - this.h;
}
//Push two paddles into the paddles array
paddles.push(new createPaddle("bottom"));
paddles.push(new createPaddle("top"));
//Setting up the parameters of ball
ball = {
x: 2,
y: 2,
r: 5,
c: "white",
vx: 4,
vy: 8,
draw: function() {
ctx.beginPath();
ctx.fillStyle = this.c;
ctx.arc(this.x, this.y, this.r, 0, Math.PI*2, false);
ctx.fill();
}
};
//Function for creating particles
function createParticles(x, y) {
this.x = x || 0;
this.y = y || 0;
this.radius = 0.8;
this.vx = -1.5 + Math.random()*3;
this.vy = -1.5 + Math.random()*3;
}
//Draw everything on canvas
function draw() {
paintCanvas();
for(var i = 0; i < paddles.length; i++) {
p = paddles[i];
ctx.fillStyle = "white";
ctx.fillRect(p.x, p.y, p.w, p.h);
}
ball.draw();
update();
}
//Mouse Position track
function trackPosition(e) {
mouse.x = e.pageX;
mouse.y = e.pageY;
}
//function to increase speed after every 5 points
function increaseSpd() {
if(points % 4 == 0) {
ball.vx += (ball.vx < 0) ? -1 : 1;
ball.vy += (ball.vy < 0) ? -2 : 2;
}
}
//function to update positions
function update() {
//Move the paddles on mouse move
if(mouse.x && mouse.y) {
for(var i = 1; i < paddles.length; i++) {
p = paddles[i];
p.x = mouse.x - p.w/2;
}
}
//Move the ball
ball.x += ball.vx;
ball.y += ball.vy;
//Collision with paddles
p1 = paddles[1];
p2 = paddles[2];
if(ball.y >= p1.y - p1.h) {
if(ball.x >= p1.x && ball.x <= (p1.x - 2) + (p1.w + 2)){
ball.vy = -ball.vy;
points++;
increaseSpd();
particlePos.x = ball.x,
particlePos.y = ball.y;
flag = 1;
}
}
else if(ball.y <= p2.y + 2*p2.h) {
if(ball.x >= p2.x && ball.x <= (p2.x - 2) + (p2.w + 2)){
ball.vy = -ball.vy;
points++;
increaseSpd();
particlePos.x = ball.x,
particlePos.y = ball.y;
flag = 1;
}
}
//Collide with walls
if(ball.x >= W || ball.x <= 0)
ball.vx = -ball.vx;
if(ball.y > H || ball.y < 0) {
clearInterval(int);
}
if(flag == 1) {
setInterval(emitParticles(particlePos.x, particlePos.y), 1000/fps);
}
}
function emitParticles(x, y) {
for(var k = 0; k < particlesCount; k++) {
particles.push(new createParticles(x, y));
}
counter = particles.length;
for(var j = 0; j < particles.length; j++) {
par = particles[j];
ctx.beginPath();
ctx.fillStyle = "white";
ctx.arc(par.x, par.y, par.radius, 0, Math.PI*2, false);
ctx.fill();
par.x += par.vx;
par.y += par.vy;
par.radius -= 0.02;
if(par.radius < 0) {
counter--;
if(counter < 0) particles = [];
}
}
}
var int = setInterval(draw, 1000/fps);
Now, my function for emitting particles is on line 156, and I have called this function on line 151. The problem here can be because of I am not resetting the flag variable but I tried doing that and got more weird results. You can check that out here.
By resetting the flag variable, the problem of infinite particles gets resolved but now they only animate and appear when the ball collides with the paddles. So, I am now out of any solution.
I can see 2 problems here.
your main short term problem is your use of setinterval is incorrect, its first parameter is a function.
setInterval(emitParticles(particlePos.x, particlePos.y), 1000/fps);
should be
setInterval(function() {
emitParticles(particlePos.x, particlePos.y);
}, 1000/fps);
Second to this, once you start an interval it runs forever - you don't want every collision event to leave a background timer running like this.
Have an array of particles to be updated, and update this list once per frame. When you make new particles, push additional ones into it.

Categories

Resources