Flickering Canvas [duplicate] - javascript

This question already has answers here:
Flickering images in canvas animation
(2 answers)
Closed last month.
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
const global = {
hornets: [],
};
class Hornet {
constructor(x, y) {
this.x = x;
this.y = y;
this.radians = 0;
this.velocity = 0.05;
}
draw() {
const hornet = new Image();
hornet.src = "./hornet.png";
ctx.drawImage(hornet, this.x, this.y);
}
move() {
this.radians += this.velocity;
this.x -= Math.cos(this.radians) * 4;
this.y -= Math.sin(this.radians) * 4;
}
}
const drawNest = () => {
const nest = new Image();
nest.src = "./nest.png";
ctx.drawImage(nest, canvas.width / 2 - 40, canvas.height / 2 - 150);
};
const drawForest = () => {
const forest = new Image();
forest.src = "./forest.png";
ctx.drawImage(forest, 0, 0);
};
const initHornets = () => {
for (let i = 0; i < 22; i++) {
let ranX = Math.floor(Math.random() * 11) - Math.floor(Math.random() * 11);
let ranY = Math.floor(Math.random() * 11) - Math.floor(Math.random() * 11);
let x = canvas.width / 2 + i * ranX;
let y = canvas.height / 2 + i * ranY;
global.hornets.push(new Hornet(x, y));
}
};
initHornets();
const animate = () => {
ctx.fillStyle = "white";
ctx.fillRect(0, 0, canvas.width, canvas.height);
drawForest();
drawNest();
global.hornets.forEach((hornet) => {
hornet.draw();
hornet.move();
});
requestAnimationFrame(animate);
};
window.onload = () => {
requestAnimationFrame(animate);
};
I've noticed that my canvas flickers every 5-6 seconds or so. Is this a fps issue from not utilizing delta time? Could it be using the Math.cos and Math.sin trig functions are resource intensive? Or is it something else entirely?
Check out what I mean: https://brixsta.github.io/Hornet-Nest/

Disabled Hardware Acceleration in Chrome and it fixes the White Flicker!

Related

How do I repeatedly interpolate linearly between two values within a requestAnimationFrame loop

I'm trying to implement multiplayer position interpolation for my canvas game but I'm having trouble using my linear interpolation (lerp) function. I experience slight jitter when using t = 0.1 so I'm looking for some alternative way to calculate t such that movement will appear smooth to the user - or a different solution altogether.
I render a canvas as follows (simplified):
function lerp (a, b, t) {
return a + (b - a) * t;
}
function tick() {
// Process position update(s).
const t = 0.1;
position.x = lerp(position.x, target_position.x, t);
position.y = lerp(position.y, target_position.y, t);
// Camera follow by offsetting canvas transform.
update_camera();
window.requestAnimationFrame(tick);
}
function update_camera() {
const position_delta_x = position.x - initial_position.x;
const position_delta_y = position.y - initial_position.y;
const offset_x = Math.round(position_delta_x);
const offset_y = Math.round(position_delta_y);
ctx.setTransform(1, 0, 0, 1, -offset_x, -offset_y);
}
tick();
I receive about 10 updates every second via a websocket that contains new position data:
function handle_position_update(new_position) {
target_position.x = new_position.x;
target_position.y = new_position.y;
}
I've noticed the jitter is coming from my camera follow logic but I'm sure as to why this is happening.
JSFIDDLE
// Shared code.
const INITIAL_POSITION = {
x: 300,
y: 80
};
// Server-side code.
const server_state = {
x: INITIAL_POSITION.x,
y: INITIAL_POSITION.y
};
const UPDATE_TICK_RATE = 10;
const PHYSICS_TICK_RATE = 60;
setInterval(() => {
// Simulate server physics update.
const w = input[87] ? 1 : 0;
const a = input[65] ? 1 : 0;
const s = input[83] ? 1 : 0;
const d = input[68] ? 1 : 0;
const vertical = w ? 1 : s ? -1 : 0;
const horizontal = d ? 1 : a ? -1 : 0;
server_state.x += horizontal * 5;
server_state.y -= vertical * 5;
}, 1000 / PHYSICS_TICK_RATE)
setInterval(() => {
// Simulate server sending updates.
target_pos_x = server_state.x;
target_pos_y = server_state.y;
}, 1000 / UPDATE_TICK_RATE);
// Client-side code.
let target_pos_x = INITIAL_POSITION.x,
target_pos_y = INITIAL_POSITION.y;
let input = [];
window.addEventListener('keydown', e => input[e.keyCode] = true);
window.addEventListener('keyup', e => input[e.keyCode] = false);
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
const W = canvas.width = 600;
const H = canvas.height = 160;
const circle = {
position: {
x: INITIAL_POSITION.x,
y: INITIAL_POSITION.y
},
tick: function() {
let t = 0.1;
this.position.x = lerp(this.position.x, target_pos_x, t);
this.position.y = lerp(this.position.y, target_pos_y, t);
ctx.beginPath();
ctx.arc(this.position.x, this.position.y, 3, 0, 2 * Math.PI);
ctx.fillStyle = 'white'
ctx.fill();
}
}
const reference_point = {
position: {
x: 240,
y: 60
},
tick: function() {
ctx.beginPath();
ctx.arc(this.position.x, this.position.y, 3, 0, 2 * Math.PI);
ctx.fillStyle = 'red'
ctx.fill()
}
}
function tick(now) {
clear();
circle.tick();
reference_point.tick();
camera_follow();
window.requestAnimationFrame(tick);
}
tick();
function clear() {
ctx.save();
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, W, H);
ctx.fillStyle = '#000';
ctx.fillRect(0, 0, W, H);
ctx.restore();
}
function camera_follow() {
const position_delta_x = circle.position.x - INITIAL_POSITION.x;
const position_delta_y = circle.position.y - INITIAL_POSITION.y;
const offset_x = Math.round(position_delta_x);
const offset_y = Math.round(position_delta_y);
ctx.setTransform(1, 0, 0, 1, -offset_x, -offset_y);
}
function lerp(a, b, t) {
return a + (b - a) * t;
}
<canvas></canvas>
<div>WASD to move</div>

How can I reverse the direction of this square after it reaches a certain value?

I'm trying to create an idle animation where the red rectangle moves back and forth slightly in a loop. For some reason once it reaches the specified threshhold instead of proceeding to move in the opposite direction, it just stops.
What did I do wrong?
<canvas id="myCanvas" width="1500" height="500" style="border:1px solid #c3c3c3;">
Your browser does not support the canvas element.
</canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
// Spaceship structure
var shipWidth = 250;
var shipHeight = 100;
// Canvas parameters
var cWidth = canvas.width;
var cHeight = canvas.height;
// Positioning variables
var centerWidthPosition = (cWidth / 2) - (shipWidth / 2);
var centerHeightPosition = (cHeight / 2) - (shipHeight / 2);
var requestAnimationFrame = window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame;
function drawShip(){
ctx.clearRect(0, 0, cWidth, cHeight);
ctx.fillStyle = "#FF0000";
ctx.fillRect(centerWidthPosition,centerHeightPosition,shipWidth,shipHeight);
centerWidthPosition--;
if (centerWidthPosition < 400){
++centerWidthPosition;
}
requestAnimationFrame(drawShip);
}
drawShip();
</script>
#TheAmberlamps explained why it's doing that. Here I offer you a solution to achieve what I believe you are trying to do.
Use a velocity variable that changes magnitude. X position always increases by velocity value. Velocity changes directions at screen edges.
// use a velocity variable
var xspeed = 1;
// always increase by velocity
centerWidthPosition += xspeed;
// screen edges are 0 and 400 in this example
if (centerWidthPosition > 400 || centerWidthPosition < 0){
xspeed *= -1; // change velocity direction
}
I added another condition in your if that causes the object to bounce back and forth. Remove the selection after || if you don't want it doing that.
Your function is caught in a loop; once centerWidthPosition reaches 399 your conditional makes it increment back up to 400, and then it decrements back to 399.
here is another one as a brain teaser - how would go by making this animation bounce in the loop - basically turn text into particles and then reverse back to text and reverse back to particles and back to text and so on and on and on infinitely:
var random = Math.random;
window.onresize = function () {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
};
window.onresize();
var ctx = canvas.getContext('2d');
ctx.font = 'bold 50px "somefont"';
ctx.textBaseline = 'center';
ctx.fillStyle = 'rgba(255,255,255,1)';
var _particles = [];
var particlesLength = 0;
var currentText = "SOMETEXT";
var createParticle = function createParticle(x, y) {_particles.push(new Particle(x, y));};
var checkAlpha = function checkAlpha(pixels, i) {return pixels[i * 4 + 3] > 0;};
var createParticles = function createParticles() {
var textSize = ctx.measureText(currentText);
ctx.fillText(currentText,Math.round((canvas.width / 2) - (textSize.width / 2)),Math.round(canvas.height / 2));
var imageData = ctx.getImageData(1, 1, canvas.width, canvas.height);
var pixels = imageData.data;
var dataLength = imageData.width * imageData.height;
for (var i = 0; i < dataLength; i++) {
var currentRow = Math.floor(i / imageData.width);
var currentColumn = i - Math.floor(i / imageData.height);
if (currentRow % 2 || currentColumn % 2) continue;
if (checkAlpha(pixels, i)) {
var cy = ~~(i / imageData.width);
var cx = ~~(i - (cy * imageData.width));
createParticle(cx, cy);
}}
particlesLength = _particles.length;
};
var Point = function Point(x, y) {
this.set(x, y);
};
Point.prototype = {
set: function (x, y) {
x = x || 0;
y = y || x || 0;
this._sX = x;
this._sY = y;
this.reset();
},
add: function (point) {
this.x += point.x;
this.y += point.y;
},
multiply: function (point) {
this.x *= point.x;
this.y *= point.y;
},
reset: function () {
this.x = this._sX;
this.y = this._sY;
return this;
},
};
var FRICT = new Point(0.98);//set to 0 if no flying needed
var Particle = function Particle(x, y) {
this.startPos = new Point(x, y);
this.v = new Point();
this.a = new Point();
this.reset();
};
Particle.prototype = {
reset: function () {
this.x = this.startPos.x;
this.y = this.startPos.y;
this.life = Math.round(random() * 300);
this.isActive = true;
this.v.reset();
this.a.reset();
},
tick: function () {
if (!this.isActive) return;
this.physics();
this.checkLife();
this.draw();
return this.isActive;
},
checkLife: function () {
this.life -= 1;
this.isActive = !(this.life < 1);
},
draw: function () {
ctx.fillRect(this.x, this.y, 1, 1);
},
physics: function () {
if (performance.now()<nextTime) return;
this.a.x = (random() - 0.5) * 0.8;
this.a.y = (random() - 0.5) * 0.8;
this.v.add(this.a);
this.v.multiply(FRICT);
this.x += this.v.x;
this.y += this.v.y;
this.x = Math.round(this.x * 10) / 10;
this.y = Math.round(this.y * 10) / 10;
}
};
var nextTime = performance.now()+3000;
createParticles();
function clearCanvas() {
ctx.fillStyle = 'rgba(0,0,0,1)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
(function clearLoop() {
clearCanvas();
requestAnimationFrame(clearLoop);
})();
(function animLoop(time) {
ctx.fillStyle = 'rgba(255,255,255,1)';
var isAlive = true;
for (var i = 0; i < particlesLength; i++) {
if (_particles[i].tick()) isAlive = true;
}
requestAnimationFrame(animLoop);
})();
function resetParticles() {
for (var i = 0; i < particlesLength; i++) {
_particles[i].reset();
}}

How to add css in text in jquery please give me refrence

How to add css in text in jquery I have try but no way found it please help me.
let particles = [];
let frequency = 20;
// Popolate particles
setInterval(
function () {
popolate();
}.bind(this),
frequency);
let c1 = createCanvas({ width: jQuery(window).width(), height: jQuery(window).height() });
let c2 = createCanvas({ width: jQuery(window).width(), height: jQuery(window).height() });
let c3 = createCanvas({ width: jQuery(window).width(), height: jQuery(window).height() });
let tela = c1.canvas;
let canvas = c1.context;
// jQuery("body").append(tela);
jQuery("#text").append(c3.canvas);
writeText(c2.canvas, c2.context, "Create\nPublish\nDeliver")
jQuery("#text").css("background-color", "grey");
class Particle {
constructor(canvas, options) {
let random = Math.random();
this.canvas = canvas;
this.x = options.x;
this.y = options.y;
this.s = 3 + Math.random();
this.a = 0;
this.w = jQuery(window).width();
this.h = jQuery(window).height();
this.radius = 0.5 + Math.random() * 20;
this.color = this.radius > 5 ? "#FF5E4C" : "#ED413C"; //this.randomColor()
}
randomColor() {
let colors = ["#FF5E4C", "#FFFFFF"];
return colors[this.randomIntFromInterval(0, colors.length - 1)];
}
randomIntFromInterval(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
render() {
this.canvas.beginPath();
this.canvas.arc(this.x, this.y, this.radius, 0, 2 * Math.PI);
this.canvas.lineWidth = 2;
this.canvas.fillStyle = this.color;
this.canvas.fill();
this.canvas.closePath();
}
move() {
//this.swapColor()
this.x += Math.cos(this.a) * this.s;
this.y += Math.sin(this.a) * this.s;
this.a += Math.random() * 0.8 - 0.4;
if (this.x < 0 || this.x > this.w - this.radius) {
return false;
}
if (this.y < 0 || this.y > this.h - this.radius) {
return false;
}
this.render();
return true;
}}
function createCanvas(properties) {
let canvas = document.createElement('canvas');
canvas.width = properties.width;
canvas.height = properties.height;
let context = canvas.getContext('2d');
return {
canvas: canvas,
context: context };
}
function writeText(canvas, context, text) {
let size = 100;
context.font = size + "px Montserrat";
context.fillStyle = "#111111";
context.textAlign = "center";
let lineheight = 70;
let lines = text.split('\n');
for (let i = 0; i < lines.length; i++) {
context.fillText(lines[i], canvas.width / 2, canvas.height / 2 + lineheight * i - lineheight * (lines.length - 1) / 3);
}
}
function maskCanvas() {
c3.context.drawImage(c2.canvas, 0, 0, c2.canvas.width, c2.canvas.height);
c3.context.globalCompositeOperation = 'source-atop';
c3.context.drawImage(c1.canvas, 0, 0);
blur(c1.context, c1.canvas, 2);
}
function blur(ctx, canvas, amt) {
ctx.filter = `blur(jQuery{amt}px)`;
ctx.drawImage(canvas, 0, 0);
ctx.filter = 'none';
}
/*
* Function to clear layer canvas
* #num:number number of particles
*/
function popolate() {
particles.push(
new Particle(canvas, {
x: jQuery(window).width() / 2,
y: jQuery(window).height() / 2 }));
return particles.length;
}
function clear() {
canvas.globalAlpha = 0.03;
canvas.fillStyle = '#111111';
canvas.fillRect(0, 0, tela.width, tela.height);
canvas.globalAlpha = 1;
}
function update() {
clear();
particles = particles.filter(function (p) {
return p.move();
});
maskCanvas();`enter code here`
requestAnimationFrame(update.bind(this));
}
update();
// jQuery("body").append(tela);
jQuery("#text").append(c3.canvas);
writeText(c2.canvas, c2.context, "Create\nPublish\nDeliver").css("margin-left:20px");
jQuery("#text").css("background-color", "grey");
I have not found any way to add css in text please help me these
This could be a possible solution
let elementStyle = document.getElementById('text').style
elementStyle.backgroundColor = 'red'
elementStyle.marginLeft = '20px'

Adding falling objects with different colors

Here is the JavaScript for a catcher game I’m making. Some of the code was given, which is why I quite fully don’t understand how to do certain things. Right now, I’m have different faller objects that are basically red rectangles that vary in height and width. What I’m trying to do is make it so that the faller objects randomize between red and blue (blue showing up less) but I’m extremely confused as how to do so. I tried making it so that the colors added to game.fillstyle were randomized prior, but that doesn’t seem to be working. Any help or advice is greatly appreciated–doesn’t have to be an answer. I’m just looking to figure this out.
Also, if I should put all of the code in please let me know.
Here is the JSfiddle : https://jsfiddle.net/ianlizzo/4dLr48v0/7/#&togetherjs=irGLk3uxOE
(() => {
let canvas = document.getElementById("game");
let game = canvas.getContext("2d");
let lastTimestamp = 0;
const FRAME_RATE = 60;
const FRAME_DURATION = 1000 / FRAME_RATE;
let fallers = [];
let score = 0;
let colourValues = ["red", "blue"]
colourValues = {
red: "#ff0000",
blue: "#0000ff"
};
let colour = colourValues[Math.floor(Math.random()*colourValues.length)];
//ignore
//let scoreCount = document.getElementById("scoreCount”);
let showScore = function(){
scoreCount.innerHTML = "Your score is " + score;
};
let addScore = function(pointValue){
score += pointValue;
showScore();
};
let fallerIn = function(inside){
inside.captured = true;
addScore(inside.pointValue);
};
const DEFAULT_DESCENT = 0.0001; // This is per millisecond.
let Faller = function (x, y, width, height, dx = 0, dy = 0, ax = 0, ay = DEFAULT_DESCENT) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.captured = false;
this.pointValue = 5;
this.colour;
// Velocity.
this.dx = dx;
this.dy = dy;
// Acceleration.
this.ax = ax;
this.ay = ay;
};
Faller.prototype.draw = function () {
game.fillStyle = colour;
game.fillRect(this.x, this.y, this.width, this.height);
};
Faller.prototype.move = function (millisecondsElapsed) {
this.x += this.dx * millisecondsElapsed;
this.y += this.dy * millisecondsElapsed;
this.dx += this.ax * millisecondsElapsed;
this.dy += this.ay * millisecondsElapsed;
};
const DEFAULT_PLAYER_WIDTH = 65;
const DEFAULT_PLAYER_HEIGHT = 45;
const DEFAULT_PLAYER_Y = canvas.height - DEFAULT_PLAYER_HEIGHT;
let Player = function (x, y = DEFAULT_PLAYER_Y, width = DEFAULT_PLAYER_WIDTH, height = DEFAULT_PLAYER_HEIGHT) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
};
Player.prototype.draw = function () {
let grd = game.createLinearGradient(0, 200, 200, 0);
grd.addColorStop(0, "black");
grd.addColorStop(0.5, "red");
grd.addColorStop(1, "white");
game.fillStyle = grd;
game.fillRect(this.x, this.y, this.width, this.height);
game.fill();
};
let player = new Player(canvas.width / 2);
let draw = (millisecondsElapsed) => {
game.clearRect(0, 0, canvas.width, canvas.height);
fallers.forEach((faller) => {
faller.draw();
faller.move(millisecondsElapsed);
if (!(faller.captured)&&
faller.y + faller.height > canvas.height &&
faller.x + faller.width < player.x + player.width &&
faller.x > player.x){
fallerIn(faller);
}
});
player.draw();
fallers = fallers.filter((faller) => {
return faller.y < canvas.height;
});
};
const MIN_WIDTH = 10;
const WIDTH_RANGE = 20;
const MIN_HEIGHT = 10;
const HEIGHT_RANGE = 20;
const MILLISECONDS_BETWEEN_FALLERS = 750;
let fallerGenerator;
let startFallerGenerator = () => {
fallerGenerator = setInterval(() => {
let fallerWidth = Math.floor(Math.random() * WIDTH_RANGE) + MIN_WIDTH;
fallers.push(new Faller(
Math.floor(Math.random() * (canvas.width - fallerWidth)), 0,
fallerWidth, Math.floor(Math.random() * HEIGHT_RANGE) + MIN_HEIGHT
));
}, MILLISECONDS_BETWEEN_FALLERS);
};
let stopFallerGenerator = () => clearInterval(fallerGenerator);
let setPlayerPositionBasedOnMouse = (event) => {
player.x = event.clientX / document.body.clientWidth * canvas.width;
};
document.body.addEventListener("mouseenter", setPlayerPositionBasedOnMouse);
document.body.addEventListener("mousemove", setPlayerPositionBasedOnMouse);
let running = false;
let nextFrame = (timestamp) => {
if (!lastTimestamp) {
lastTimestamp = timestamp;
}
if (timestamp - lastTimestamp < FRAME_DURATION) {
if (running) {
window.requestAnimationFrame(nextFrame);
}
return;
}
draw(timestamp - lastTimestamp);
lastTimestamp = timestamp;
if (running) {
window.requestAnimationFrame(nextFrame);
}
};
document.getElementById("start-button").addEventListener("click", () => {
running = true;
lastTimestamp = 0;
startFallerGenerator();
window.requestAnimationFrame(nextFrame);
});
document.getElementById("stop-button").addEventListener("click", () => {
stopFallerGenerator();
running = false;
});
})();
let colourValues = ["red", "blue"]
/* colourValues.length will be undefined for object.
colourValues = {
red: "#ff0000",
blue: "#0000ff"
};*/
let colour = colourValues[Math.floor(Math.random()*colourValues.length)];
See this fiddle
Random color generator should generate red for 75% times.
Faller.prototype.randomColour = function() {
return colourValues[Math.floor(Math.random() * colourValues.length * 0.75)];
};
Faller should use its own color to fill
Faller.prototype.draw = function() {
game.fillStyle = this.colour;
game.fillRect(this.x, this.y, this.width, this.height);
};
which was assigned in Faller constructor.
this.colour = this.randomColour();
I couldn't figure out how to set ES6 in jsFiddle. So it is done in ES5
let colourValues = ["red", "blue", "red", "red"];
game.fillStyle = colourValues[Math.floor(Math.random()*colourValues.length)];
plnkr http://plnkr.co/edit/uY5hm8Pkaoklfr6Tikrd?p=preview

Canvas unable to find context when requestAnimationFrame is called - ES6 [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 7 years ago.
I am experimenting with class based code. I create a class for the canvas and pass a component to it which is then rendered. The problem is that when the browser requests the animation frame the context is lost, and becomes undefined. I am looking for an explanation of why this is the case.
I am not concerned with best practice just with figuring out why the context is lost.
I have attached a link to the example on codepen.
http://codepen.io/BrianDGLS/pen/BoJorM?editors=001
Here is the JS code:
class Canvas {
constructor() {
this.canvas = document.getElementById('canvas');
this.context = this.canvas.getContext('2d');
this.width = this.canvas.width = window.innerHeight;
this.height = this.canvas.height = window.innerWidth;
this.components = [];
}
draw() {
this.context.clearRect(0, 0, this.width, this.height);
this.context.globalCompositeOperation = 'hard-light';
this.components.map(_ => _.render());
window.requestAnimationFrame(this.draw);
}
listeners() {
window.addEventListener('resize', () => {
this.width = this.canvas.width = window.innerHeight;
this.height = this.canvas.height = window.innerWidth;
}, false);
}
init() {
this.listeners();
this.draw();
}
}
class Utils {
randomNum(max, min) {
return Math.floor(max * Math.random()) + min;
}
color(opacity) {
return `hsla(${this.randomNum(360, 1)}, 70%, 60%, ${opacity})`;
}
}
const utils = new Utils();
const _canvas = new Canvas();
class Stars {
constructor(_) {
this.total = _.total;
this.spawn = [];
this.z = 300;
this.canvas = _.canvas;
this.xw = this.canvas.width * this.z;
this.xh = this.canvas.height * this.z;
}
create() {
while (this.spawn.length < this.total) {
this.spawn.push({
pos: [this.xw * Math.random() - this.canvas.width / 2 * this.z, this.xh * Math.random() - this.canvas.height / 2 * this.z, this.z],
vel: [0, 0, -2],
r: utils.randomNum(500, 100),
color: utils.color(1)
});
}
}
draw() {
for (let i = 0; i < this.spawn.length; ++i) {
let t = this.spawn[i];
let x = t.pos[0] / t.pos[2];
let y = t.pos[1] / t.pos[2];
if (x < -this.canvas.width / 2 || x > this.canvas.width / 2 || y < -this.canvas.height / 2 || y > this.canvas.height / 2 || t.pos[2] < 0) {
this.spawn.splice(i, 1);
--i;
continue;
}
this.canvas.context.beginPath();
this.canvas.context.fillStyle = t.color;
this.canvas.context.arc(x, y, t.r / t.pos[2], 0, Math.PI * 2, false);
t.pos[0] += t.vel[0];
t.pos[1] += t.vel[1];
t.pos[2] += t.vel[2];
this.canvas.context.fill();
}
}
render() {
this.create();
this.canvas.context.save();
this.canvas.context.translate(this.canvas.width / 2, this.canvas.height / 2);
this.draw();
this.canvas.context.restore();
}
}
_canvas.components.push(new Stars({
canvas: _canvas,
total: 200
}));
When you invoke draw() via window.requestAnimationFrame(this.draw) the scope in draw() is bound to window instead of Canvas. Try binding the scope explicitly like this:
window.requestAnimationFrame(this.draw.bind(this));

Categories

Resources