Shouldn't this "if statement" cause a bounce? - javascript

The if statement in question is:
if (
this.y + this.radius == lineInfo.loneSy &&
this.x + this.radius > lineInfo.loneSx &&
this.x + this.radius < lineInfo.loneEx
)
{
this.dy = -this.dy; //linebounce
}
I know for sure that the first two conditions work properly because if I omit the third conditional of: this.x + this.radius < lineInfo.loneEx, the ball bounces as expected, however when I add the third conditional in an attempt to constrict its bounce to only within the length of the line; the ball doesn't bounce at all - even though it should.
The entire code for reference is:
let canvas = document.getElementById('myCanvas');
let c = canvas.getContext('2d'); //c = super object (methods / functions) 2d
const sceneObjects = [];
let lineReact = {
jitter: false,
hitOne: false,
hitTwo: false,
hitThree: false,
hitFour: false
}
let lineInfo = {
loneSx: 0,
loneSy: 0,
loneEx: 0,
loneEy: 0
}
window.addEventListener('load',
function(e){
lineReact.jitter == true ? (lineReact.jitter = false) : (lineReact.jitter = true);
if (lineReact.jitter == true){
setTimeout(function(){
lineReact.jitter = false;
console.log("Time lapse " + lineReact.jitter);
}, 300);
}
console.log(lineReact.jitter);
}
)
function Square(x, y, width, height, color){
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.color = color;
this.draw = function(){
c.fillStyle = this.color;
c.fillRect(this.x, this.y, this.width, this.height);
}
this.update = function(){
this.draw();
}
}
function Line(startX, startY, endX, endY, color, lNumber){
this.startX = startX;
this.startY = startY;
this.endX = endX;
this.endY = endY;
this.color = color;
this.lockSx = this.startX;
this.lockSy = this.startY;
this.lockEx = this.endX;
this.lockEy = this.endY;
this.draw = function(){
c.beginPath();
c.strokeStyle = this.color;
c.moveTo(this.startX, this.startY);
c.lineTo(this.endX, this.endY);
c.stroke();
}
this.update = function(){
if (lineReact.jitter == false){
this.color = "white";
this.startX = this.lockSx;
this.startY = this.lockSy;
this.endX = this.lockEx;
this.endY = this.lockEy;
} else {
if(lNumber == 1){
lineInfo.loneSx = this.lockSx;
lineInfo.loneSy = this.lockSy;
lineInfo.loneEx = this.lockEx;
lineInfo.loneEy = this.lockEy;
this.startX -= Math.floor(Math.random() * 2);
this.startY += Math.floor(Math.random() * 2);
this.endX += Math.floor(Math.random() * 2);
this.endY += Math.floor(Math.random() * 2);
this.color = "red";
}
if(lNumber == 2){
this.startX -= Math.floor(Math.random() * 2);
this.startY -= Math.floor(Math.random() * 2);
this.endX -= Math.floor(Math.random() * 2);
this.endY += Math.floor(Math.random() * 2);
this.color = "red";
}
if(lNumber == 3){
this.startX -= Math.floor(Math.random() * 2);
this.startY -= Math.floor(Math.random() * 2);
this.endX += Math.floor(Math.random() * 2);
this.endY -= Math.floor(Math.random() * 2);
this.color = "red";
}
if(lNumber == 4){
this.startX += Math.floor(Math.random() * 2);
this.startY -= Math.floor(Math.random() * 2);
this.endX += Math.floor(Math.random() * 2);
this.endY += Math.floor(Math.random() * 2);
this.color = "red";
}
}
this.draw();
//console.log('test read ' + lineInfo.loneSx);
}
}
function Circle(x, y, dx, dy, radius){
this.x = x;
this.y = y;
this.dx = dx;
this.dy = dy;
this.radius = radius;
this.draw = function(){
c.beginPath();
c.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
c.strokeStyle = 'black';
c.fillStyle = 'black';
c.fill();
c.stroke();
}
this.update = function(){
if (this.x + this.radius > canvas.width || this.x - this.radius < 0){
this.dx = -this.dx; // wallbounce
}
if (this.y + this.radius > canvas.height || this.y - this.radius < 0){
this.dy = -this.dy; // wallbounce
}
if (
this.y + this.radius == lineInfo.loneSy &&
this.x + this.radius > lineInfo.loneSx &&
this.x + this.radius < lineInfo.loneEx
)
{
this.dy = -this.dy; //linebounce
}
this.x += this.dx; //velocity
this.y += this.dy; //velocity
this.draw();
}
}
let square = new Square(280, 280, 40, 40, "pink");
let circle = new Circle(245, 195, 1, 1, 6);
let lineOne = new Line(280, 270, 320, 270, "white", 1);
let lineTwo = new Line(330, 280, 330, 320, "white", 2);
let lineThree = new Line(280, 330, 320, 330, "white", 3);
let lineFour = new Line(270, 280, 270, 320, "white", 4);
function animate() {
requestAnimationFrame(animate);
c.clearRect(0, 0, canvas.width, canvas.height);
square.update();
lineOne.update();
lineTwo.update();
lineThree.update();
lineFour.update();
circle.update();
}
animate();
body {
background-color: black;
margin: 0;
}
#myCanvas {
position: absolute;
top: 50%;
left: 50%;
background-color: #385D72;
margin: -300px 0 0 -300px;
}
<canvas id="myCanvas" width="600" height="600">

You need to use || instead of &&:
if (
this.y + this.radius == lineInfo.loneSy &&
(this.x + this.radius < lineInfo.loneSx || this.x + this.radius > lineInfo.loneEx)
)
{
this.dy = -this.dy; //linebounce
}
With && you're testing if both conditions are true, but it's impossible for both to be true at the same time (the ball can't be both to the left of the line and to the right of the line).

Related

How to arrange and style buttons in canvas?

let canvas = document.getElementById("canvas");
let context = canvas.getContext("2d");
// for canvas size
var window_width = window.innerWidth;
var window_height = window.innerHeight;
canvas.style.background="yellow"
canvas.width = window_width;
canvas.height = window_height;
let hit_counter=0;
function randomIntFromInterval(min, max) { // min and max included
return Math.floor(Math.random() * (max - min + 1) + min)
}
class Circle {
constructor(xpos, ypos, radius, color, text) {
this.position_x = xpos;
this.position_y = ypos;
this.radius = radius;
this.text = text;
this.color = color;
}
// creating circle
draw(context) {
context.beginPath();
context.strokeStyle = this.color;
context.fillText(this.text, this.position_x, this.position_y);
context.textAlign = "center";
context.textBaseline = "middle"
context.font = "20px Arial";
context.lineWidth = 5;
context.arc(this.position_x, this.position_y, this.radius, 0, Math.PI * 2);
context.stroke();
context.closePath();
}
update() {
this.text=hit_counter;
context.clearRect(0, 0, window_width, window_height)
this.draw(context);
if ((this.position_x + this.radius) > window_width) {
this.dx = -this.dx;
}
if ((this.position_x - this.radius) < 0) {
this.dx = -this.dx;
}
if ((this.position_y - this.radius) < 0) {
this.dy = -this.dy;
}
if ((this.position_y + this.radius) > window_height) {
this.dy = -this.dy;
}
this.position_x += this.dx;
this.position_y += this.dy;
}
}
let my_circle = new Circle(100, 100, 50, 'Black', hit_counter);
my_circle.update();
<button>ex1</button>
<button>ex2</button>
<button>ex3</button>
<button>ex4</button>
<button>ex5</button>
<button>ex6</button>
<button>ex7</button>
<button>ex8</button>
<canvas id="canvas"></canvas>
HTML
How to arrange and style buttons in canvas? I tried adding CSS to buttons but it didn't work for me.. How to do that? How to arrange the buttons in center of canvas?
<button>ex1</button>
<button>ex2</button>
<button>ex3</button>
<button>ex4</button>
<button>ex5</button>
<button>ex6</button>
<button>ex7</button>
<button>ex8</button>
<canvas id="canvas"></canvas>
JS
How to arrange and style buttons in canvas. I tried adding CSS to buttons but it didn't work for me.. How to do that? How to arrange the buttons in center of canvas?
let canvas = document.getElementById("canvas");
let context = canvas.getContext("2d");
// for canvas size
var window_width = window.innerWidth;
var window_height = window.innerHeight;
canvas.style.background="yellow"
canvas.width = window_width;
canvas.height = window_height;
let hit_counter=0;
function randomIntFromInterval(min, max) { // min and max included
return Math.floor(Math.random() * (max - min + 1) + min)
}
class Circle {
constructor(xpos, ypos, radius, color, text) {
this.position_x = xpos;
this.position_y = ypos;
this.radius = radius;
this.text = text;
this.color = color;
}
// creating circle
draw(context) {
context.beginPath();
context.strokeStyle = this.color;
context.fillText(this.text, this.position_x, this.position_y);
context.textAlign = "center";
context.textBaseline = "middle"
context.font = "20px Arial";
context.lineWidth = 5;
context.arc(this.position_x, this.position_y, this.radius, 0, Math.PI * 2);
context.stroke();
context.closePath();
}
update() {
this.text=hit_counter;
context.clearRect(0, 0, window_width, window_height)
this.draw(context);
if ((this.position_x + this.radius) > window_width) {
this.dx = -this.dx;
}
if ((this.position_x - this.radius) < 0) {
this.dx = -this.dx;
}
if ((this.position_y - this.radius) < 0) {
this.dy = -this.dy;
}
if ((this.position_y + this.radius) > window_height) {
this.dy = -this.dy;
}
this.position_x += this.dx;
this.position_y += this.dy;
}
}
let my_circle = new Circle(100, 100, 50, 'Black', hit_counter);
my_circle.update();
you can put your buttons inside of a container and position it with absolute property in css
let canvas = document.getElementById("canvas");
let context = canvas.getContext("2d");
// for canvas size
var window_width = window.innerWidth;
var window_height = window.innerHeight;
canvas.style.background="yellow"
canvas.width = window_width;
canvas.height = window_height;
let hit_counter=0;
function randomIntFromInterval(min, max) { // min and max included
return Math.floor(Math.random() * (max - min + 1) + min)
}
class Circle {
constructor(xpos, ypos, radius, color, text) {
this.position_x = xpos;
this.position_y = ypos;
this.radius = radius;
this.text = text;
this.color = color;
}
// creating circle
draw(context) {
context.beginPath();
context.strokeStyle = this.color;
context.fillText(this.text, this.position_x, this.position_y);
context.textAlign = "center";
context.textBaseline = "middle"
context.font = "20px Arial";
context.lineWidth = 5;
context.arc(this.position_x, this.position_y, this.radius, 0, Math.PI * 2);
context.stroke();
context.closePath();
}
update() {
this.text=hit_counter;
context.clearRect(0, 0, window_width, window_height)
this.draw(context);
if ((this.position_x + this.radius) > window_width) {
this.dx = -this.dx;
}
if ((this.position_x - this.radius) < 0) {
this.dx = -this.dx;
}
if ((this.position_y - this.radius) < 0) {
this.dy = -this.dy;
}
if ((this.position_y + this.radius) > window_height) {
this.dy = -this.dy;
}
this.position_x += this.dx;
this.position_y += this.dy;
}
}
let my_circle = new Circle(100, 100, 50, 'Black', hit_counter);
my_circle.update();
.container{
position:absolute;
}
.container .buttons{
position: absolute;
top:0px;
padding:0.5rem;
}
.container .buttons button{
background:transparent;
padding:0.5rem;
}
<div class="container">
<div class="buttons">
<button>ex1</button>
<button>ex2</button>
<button>ex3</button>
<button>ex4</button>
<button>ex5</button>
<button>ex6</button>
<button>ex7</button>
<button>ex8</button>
</div>
<canvas id="canvas"></canvas>
</div>

Javascript text particle in canvas slow in firefox but not on chrome (requestAnimationFrame ?)

I'm struggling with the implementation of a text particle in javascript.
My code is working fine with chromium-based browsers (Chromium: 84) but is unexpectedly slow on firefox (79.0).
I've searched a lot, but still don't find a solution and where the problem is.(This is pretty much linked to this Javascript Animation(Canvas) not working in firefox, Edge but works on Chrome).
Here is my codepen:
https://codepen.io/jgazeau/pen/LYNYPYB
function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
function getCssVar(v) {
return getComputedStyle(document.documentElement).getPropertyValue(v);
}
let text404 = '404';
let canvas = document.getElementById('scene');
let ch = canvas.height = canvas.getBoundingClientRect().height;
let cw = canvas.width = canvas.getBoundingClientRect().width;
let sceneBackground = getCssVar('--scene-background');
let context = canvas.getContext('2d');
let previousMouseCoord = {x:0, y:0};
let mouseCoord = {x:0, y:0};
let sceneResize = false;
let particlesCount = 0;
let particles = [];
let colors = [
getCssVar('--particle-color-1'),
getCssVar('--particle-color-2'),
getCssVar('--particle-color-3'),
getCssVar('--particle-color-4'),
getCssVar('--particle-color-5')
];
const dpi = 200;
let Particle = function(x, y) {
this.x = getRandomInt(cw);
this.y = getRandomInt(ch);
this.coord = {x:x, y:y};
this.r = Math.min((getRandomInt((cw / dpi)) + 1), 6);
this.vx = (Math.random() - 0.5) * 100;
this.vy = (Math.random() - 0.5) * 100;
this.accX = 0;
this.accY = 0;
this.friction = Math.random() * 0.05 + 0.90;
this.color = colors[Math.floor(Math.random() * 6)];
}
Particle.prototype.render = function(isDisableMouse) {
this.accX = (this.coord.x - this.x) / 100;
this.accY = (this.coord.y - this.y) / 100;
this.vx += this.accX;
this.vy += this.accY;
this.vx *= this.friction;
this.vy *= this.friction;
this.x += this.vx;
this.y += this.vy;
if (!isDisableMouse) {
let a = this.x - mouseCoord.x;
let b = this.y - mouseCoord.y;
var distance = Math.sqrt(a * a + b * b);
if(distance < (cw / 15)) {
this.accX = (this.x - mouseCoord.x) / 100;
this.accY = (this.y - mouseCoord.y) / 100;
this.vx += this.accX;
this.vy += this.accY;
}
}
context.fillStyle = this.color;
context.beginPath();
context.arc(this.x, this.y, this.r, 0, Math.PI * 2, false);
context.fill();
context.closePath();
}
function onmouseCoordMove(e) {
mouseCoord.x = e.clientX;
mouseCoord.y = e.clientY;
}
function onTouchMove(e) {
if(e.touches.length > 0 ) {
mouseCoord.x = e.touches[0].clientX;
mouseCoord.y = e.touches[0].clientY;
}
}
function onTouchEnd() {
mouseCoord.x = -9999;
mouseCoord.y = -9999;
}
function initScene() {
ch = canvas.height = canvas.getBoundingClientRect().height;
cw = canvas.width = canvas.getBoundingClientRect().width;
context.clearRect(0, 0, canvas.width, canvas.height);
context.font = 'bold ' + (cw / 5) + 'px sans-serif';
context.fillStyle = sceneBackground;
context.textAlign = 'center';
context.fillText(text404, cw / 2, ch / 2);
let imageData = context.getImageData(0, 0, cw, ch).data;
context.clearRect(0, 0, canvas.width, canvas.height);
context.globalCompositeOperation = 'screen';
particles = [];
for(let y = 0; y < ch; y += Math.round(cw / dpi)) {
for(let x = 0; x < cw; x += Math.round(cw / dpi)) {
if(imageData[((x + y * cw) * 4) + 3] > 128){
particles.push(new Particle(x, y));
}
}
}
particlesCount = particles.length;
}
function renderScene() {
context.clearRect(0, 0, canvas.width, canvas.height);
let isDisableMouse = false;
if ((previousMouseCoord.x === mouseCoord.x) && (previousMouseCoord.x === mouseCoord.x)) {
isDisableMouse = true;
} else {
previousMouseCoord.x = mouseCoord.x;
previousMouseCoord.x = mouseCoord.x;
isDisableMouse = false;
}
for (let i = 0; i < particlesCount; i++) {
particles[i].render(isDisableMouse);
}
requestAnimationFrame(renderScene);
};
document.addEventListener('DOMContentLoaded', function() {
initScene();
renderScene();
window.addEventListener('mousemove', onmouseCoordMove);
window.addEventListener('touchmove', onTouchMove);
window.addEventListener('touchend', onTouchEnd);
window.addEventListener('resize', function() {
if (!sceneResize) {
requestAnimationFrame(function() {
initScene();
sceneResize = false;
});
sceneResize = true;
}
});
});
Can anyone know where this slow issue could come from ?
Thanks a lot for your help.

How to give each circle a random color?

I can't figure out how to give all the different circles a random color. Right now my code gives all the circles the same color but it switches when you refresh.
I want it to give all the circles different colors. I have tried two ways but they don't seem to work.
Here is my code
var can = document.getElementById('canvas');
can.width = window.innerWidth;
can.height = window.innerHeight;
var ctx = can.getContext('2d');
function Circle(centerX, centerY, speedX, speedX, radius) {
this.centerX = centerX;
this.centerY = centerY;
this.speedX = speedX;
this.speedY = speedY;
this.radius = radius;
this.draw = function () {
ctx.beginPath();
ctx.arc(this.centerX, this.centerY, this.radius, 0, Math.PI * 2);
ctx.fill();
}
this.update = function () {
this.ctx.fillStyle =
this.centerX += this.speedX;
if (this.centerX + this.radius > innerWidth || this.centerX - this.radius < 0) {
this.speedX = -this.speedX;
}
this.centerY += this.speedY;
if (this.centerY + this.radius > innerHeight || this.centerY - this.radius < 0) {
this.speedY = -this.speedY;
}
this.draw();
}
}
var circleArray = [];
var circleAmount = 45;
for (var i = 0; i < circleAmount; i++) {
var centerX = Math.random() * window.innerWidth;
var centerY = Math.random() * window.innerWidth;
var radius = (Math.random() * 24) + 3;
ctx.fillStyle = 'rgba(' + Math.floor(Math.random() * 255) + ',' + Math.floor(Math.random() * 255) + ',' + Math.floor(Math.random() * 255) + ',' + ".5" + ')';
var speedY = (Math.random() - 0.5) * 3;
var speedX = (Math.random() - 0.5) * 6;
circleArray.push(new Circle(centerX, centerY, speedX, speedY, radius));
}
function draw() {
requestAnimationFrame(draw);
ctx.clearRect(0, 0, innerWidth, innerHeight);
for(var i = 0; i < circleArray.length; i++){
circleArray[i].update();
}
}
draw();
Pass the color to the Circle constructor function, and set the fillColor in the update function:
var can = document.getElementById('canvas');
can.width = window.innerWidth;
can.height = window.innerHeight;
var ctx = can.getContext('2d');
function Circle(centerX, centerY, speedX, speedX, radius, color) {
this.centerX = centerX;
this.centerY = centerY;
this.speedX = speedX;
this.speedY = speedY;
this.radius = radius;
this.color = color;
this.draw = function() {
ctx.beginPath();
ctx.fillStyle = this.color;
ctx.arc(this.centerX, this.centerY, this.radius, 0, Math.PI * 2);
ctx.fill();
}
this.update = function() {
this.centerX += this.speedX;
if (this.centerX + this.radius > innerWidth || this.centerX - this.radius < 0) {
this.speedX = -this.speedX;
}
this.centerY += this.speedY;
if (this.centerY + this.radius > innerHeight || this.centerY - this.radius < 0) {
this.speedY = -this.speedY;
}
this.draw();
}
}
var circleArray = [];
var circleAmount = 45;
for (var i = 0; i < circleAmount; i++) {
var centerX = Math.random() * window.innerWidth;
var centerY = Math.random() * window.innerWidth;
var radius = (Math.random() * 24) + 3;
var color = 'rgba(' + Math.floor(Math.random() * 255) + ',' + Math.floor(Math.random() * 255) + ',' + Math.floor(Math.random() * 255) + ',' + ".5" + ')';
var speedY = (Math.random() - 0.5) * 3;
var speedX = (Math.random() - 0.5) * 6;
circleArray.push(new Circle(centerX, centerY, speedX, speedY, radius, color));
}
function draw() {
requestAnimationFrame(draw);
ctx.clearRect(0, 0, innerWidth, innerHeight);
for (var i = 0; i < circleArray.length; i++) {
circleArray[i].update();
}
}
draw();
<canvas id="canvas"></canvas>

Javascript Animation(Canvas) not working in firefox, Edge but works on Chrome

This is a code from codepen. I am trying to work on this one. This code works on chrome but does not work in firefox or edge. I tried to solve the issue but could not fix it. Is the problem with requestAnimationFrame or something else? Can anyone please help? Here is the codepen link: https://codepen.io/iremlopsum/pen/MKNaxd
var canvas = document.querySelector("#scene"),
ctx = canvas.getContext("2d"),
particles = [],
amount = 0,
mouse = {
x: 0,
y: 0
},
radius = 0.7; //Init radius of the force field
var colors = ["rgba(255,255,255, .6)", "rgba(255,255,255, .6)", "rgba(255,255,255, .6)", "rgba(255,255,255, .6)", "rgba(255,255,255, .6)", "rgba(255,255,255, .6)"];
var colorsTwo = ["rgba(255,255,255, .6)", "rgba(255,255,255, .6)", "rgba(255,255,255, .6)", "rgba(255,255,255, .6)", "rgba(255,255,255, .6)", "rgba(255,255,255, .6)"];
var copy = "Mighty Byte"; // Text to display
var initSize = Math.floor(Math.random() * .6) + 1 ;
var hoverSize = initSize + .7;
var ww = canvas.width = window.innerWidth;
var wh = canvas.height = window.innerHeight;
function Particle(x, y) {
this.x = Math.random() * ww;
this.y = Math.random() * wh;
this.dest = {
x: x,
y: y
};
//this.r = Math.random() * 1; // the size of bubbles
this.vx = (Math.random() - 0.5) * 2;
this.vy = (Math.random() - 0.5) * 2;
this.accX = 0;
this.accY = 0;
this.friction = Math.random() * 0.015 + 0.94; // force of bounce, just try to change 0.015 to 0.5
//this.color = colors[Math.floor(Math.random() * 10)];
//this.colorTwo = colorsTwo[Math.floor(Math.random() * 10)];
}
Particle.prototype.render = function() {
this.accX = (this.dest.x - this.x) / 200; //acceleration for X
this.accY = (this.dest.y - this.y) / 200; //acceleration for Y
this.vx += this.accX;
this.vy += this.accY;
this.vx *= this.friction;
this.vy *= this.friction;
this.x += this.vx;
this.y += this.vy;
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(this.x, this.y, this.r, Math.PI * 2, false);
ctx.fill();
var a = this.x - mouse.x;
var b = this.y - mouse.y;
var distance = Math.sqrt(a * a + b * b);
if (distance < (radius * 70)) {
this.accX = (this.x - mouse.x) / 20; //acceleration on mouseover X, smaller faster
this.accY = (this.y - mouse.y) / 20; //acceleration on mouseover Y, smaller faster
this.vx += this.accX;
this.vy += this.accY;
//ctx.fillStyle = this.colorTwo;
}
if (distance < (radius * 70)) {
this.colorTwo = colorsTwo[Math.floor(Math.random() * 10)];
ctx.fillStyle = this.colorTwo;
this.r = hoverSize; // the size of bubbles
}
if (distance > (radius * 70)) {
this.colorOne = colors[Math.floor(Math.random() * 10)];
ctx.fillStyle = this.colorOne;
this.r = initSize
}
}
function onMouseMove(e) {
mouse.x = e.clientX;
mouse.y = e.clientY;
}
function initScene() {
ww = canvas.width = window.innerWidth;
wh = canvas.height = window.innerHeight;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.font = "bold " + (ww / 10) + "px sans-serif"; // Size of the text
ctx.textAlign = "center";
ctx.fillText(copy, ww / 2, wh / 2); //Centering
var data = ctx.getImageData(0, 0, ww, wh).data;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.globalCompositeOperation = "screen";
particles = [];
for (var i = 0; i < ww; i += Math.round(ww / 400)) { //400 here represents the amount of particles
for (var j = 0; j < wh; j += Math.round(ww / 400)) {
if (data[((i + j * ww) * 4) + 3] > 250) {
particles.push(new Particle(i, j));
}
}
}
amount = particles.length;
}
function onMouseClick() {
radius = 4; //onclick expand radius
}
function offMouseClick() {
radius = 0.5; //offClick init radius
}
function delayedInitRadius() {
setTimeout(offMouseClick, 500); //delay for offClick init radius
}
function render(a) {
requestAnimationFrame(render);
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < amount; i++) {
particles[i].render();
}
};
window.addEventListener("resize", initScene);
window.addEventListener("mousemove", onMouseMove);
window.addEventListener("mousedown", onMouseClick);
window.addEventListener("mouseup", delayedInitRadius);
initScene();
requestAnimationFrame(render);

Event Listener only listening to two figures on the screen in Javascript and HTML Canvas

I have run into a problem with my program, which essentially moves 100 figures on a browser window and changes their direction if the user presses a key down. In order to determine if a user has pressed a key, I used an event listener, but the problem is that the event listener only works for two of the figures on the screen. I can only change the direction of two figures, while the other figures continue to move around the screen and not respond to user input. I have attached all of my code below, and I would really appreciate if someone could help me figure out the problem! Thanks!
let canvas = document.querySelector("canvas")
canvas.width = window.innerWidth
canvas.height = window.innerHeight
// console.log(innerWidth)
// console.log(innerHeight)
let c = canvas.getContext("2d")
let changeDirection = undefined
let repeatone = 0
let repeattwo = 0
window.addEventListener('keydown', function(event) {
repeatone = 0
repeattwo = 0
changeDirection = true
console.log(changeDirection)
})
window.addEventListener('keyup', function(event) {
changeDirection = false
console.log(changeDirection);
})
function random_rgba() {
var o = Math.round,
r = Math.random,
s = 255;
return 'rgba(' + o(r() * s) + ',' + o(r() * s) + ',' + o(r() * s) + ',' + r().toFixed(1) + ')';
}
// c.arc(xCircle, yCircle, radius, 0, Math.PI * 2, false)
function Circle(x, y, dx, dy, radius, color) {
this.x = x
this.y = y
this.dx = dx
this.dy = dy
this.radius = radius
this.color = color
this.draw = function() {
// c.strokeStyle = this.color
c.beginPath()
c.strokeStyle = this.color
c.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false)
c.stroke()
}
this.update = function() {
repeatone += 1
if (changeDirection === true && repeatone <= 1) {
this.dx = -this.dx
this.dy = -this.dy
if (this.x >= innerWidth - this.radius) {
this.dx = -this.dx
} else if (this.x <= 0) {
this.dx = -this.dx
}
if (this.y >= innerHeight - this.radius) {
this.dy = -this.dy
} else if (this.y <= 0) {
this.dy = -this.dy
}
this.x += this.dx
this.y += this.dy
this.draw()
} else if (changeDirection === false || repeatone > 1) {
if (this.x >= innerWidth - this.radius) {
this.dx = -this.dx
} else if (this.x <= 0) {
this.dx = -this.dx
}
if (this.y >= innerHeight - this.radius) {
this.dy = -this.dy
} else if (this.y <= 0) {
this.dy = -this.dy
}
this.x += this.dx
this.y += this.dy
this.draw()
}
}
}
function Rectangle(x, y, dx, dy, height, width, color) {
this.x = x
this.y = y
this.dx = dx
this.dy = dy
this.height = height
this.width = width
this.color = color
this.draw = function() {
c.beginPath()
c.fillStyle = this.color
c.fillRect(this.x, this.y, this.width, this.height)
}
this.update = function() {
repeattwo += 1
if (changeDirection === true && repeattwo <= 1) {
this.dx = -this.dx
this.dy = -this.dy
if (this.x >= innerWidth - this.width) {
this.dx = -this.dx
} else if (this.x <= 0) {
this.dx = -this.dx
}
if (this.y >= innerHeight - this.height) {
this.dy = -this.dy
} else if (this.y <= 0) {
this.dy = -this.dy
}
this.x += this.dx
this.y += this.dy
this.draw()
} else if (changeDirection === false || repeattwo > 1) {
if (this.x >= innerWidth - this.width) {
this.dx = -this.dx
} else if (this.x <= 0) {
this.dx = -this.dx
}
if (this.y >= innerHeight - this.height) {
this.dy = -this.dy
} else if (this.y <= 0) {
this.dy = -this.dy
}
this.x += this.dx
this.y += this.dy
this.draw()
}
}
}
// let x = Math.floor((Math.random() * innerWidth) + 1)
// let dx = Math.floor((Math.random() * 10) + 1)
// let y = Math.floor((Math.random() * innerHeight) + 1)
// let dy = Math.floor((Math.random() * 10) + 1)
//
// console.log("X Value " + x)
// console.log("Y Value " + y)
// console.log("X Velocity Value " + dx)
// console.log("Y Velocity Value " + dy)
//
let rectangleArray = []
let circleArray = []
for (var i = 0; i < 50; i++) {
let xRect = Math.floor((Math.random() * innerWidth) + 1)
let dxRect = Math.floor((Math.random() * 10) + 1)
let yRect = Math.floor((Math.random() * innerHeight) + 1)
let dyRect = Math.floor((Math.random() * 10) + 1)
let heightRect = Math.floor((Math.random() * 250) + 1)
let widthRect = Math.floor((Math.random() * 250) + 1)
let colorRect = random_rgba()
let xCircle = Math.floor((Math.random() * innerWidth) + 1)
let dxCircle = Math.floor((Math.random() * 10) + 1)
let yCircle = Math.floor((Math.random() * innerHeight) + 1)
let dyCircle = Math.floor((Math.random() * 10) + 1)
let heightCircle = Math.floor((Math.random() * 250) + 1)
let widthCircle = Math.floor((Math.random() * 250) + 1)
let colorCircle = random_rgba()
let radiusCircle = Math.floor((Math.random() * 100) + 1)
rectangleArray.push(new Rectangle(xRect, yRect, dxRect, dyRect, heightRect, widthRect, colorRect))
circleArray.push(new Circle(xCircle, yCircle, dxCircle, dyCircle, radiusCircle, colorCircle))
}
console.log(circleArray)
console.log(rectangleArray)
function animate() {
requestAnimationFrame(animate)
c.clearRect(0, 0, innerWidth, innerHeight)
for (var i = 0; i < rectangleArray.length; i++) {
rectangleArray[i].draw()
rectangleArray[i].update()
}
for (var i = 0; i < circleArray.length; i++) {
circleArray[i].draw()
circleArray[i].update()
}
}
animate()
<canvas></canvas>
You had a lot of code, I remove a lot of it...
Take a look at the new logic under the addEventListener
Troubleshooting cases like this the first thing I do is reduce the scope:
you had 100 figures, I took it down to 6
your animation was too fast, I reduced the speed.
lot's of random stuff on the code that created the figures, I hard-coded some of that.
you had changeDirection, repeatone & repeattwo, I could not figure out what you needed those for so I remove them.
let canvas = document.querySelector("canvas")
canvas.width = canvas.height = innerWidth = innerHeight = 300
let c = canvas.getContext("2d")
window.addEventListener('keydown', function(event) {
for (var i = 0; i < rectangleArray.length; i++) {
rectangleArray[i].dx *= -1
rectangleArray[i].dy *= -1
}
for (var i = 0; i < circleArray.length; i++) {
circleArray[i].dx *= -1
circleArray[i].dy *= -1
}
})
function random_rgba() {
var o = Math.round,
r = Math.random,
s = 255;
return 'rgba(' + o(r() * s) + ',' + o(r() * s) + ',' + o(r() * s) + ',' + r().toFixed(1) + ')';
}
// c.arc(xCircle, yCircle, radius, 0, Math.PI * 2, false)
function Circle(x, y, dx, dy, radius, color) {
this.x = x
this.y = y
this.dx = dx
this.dy = dy
this.radius = radius
this.color = color
this.draw = function() {
// c.strokeStyle = this.color
c.beginPath()
c.strokeStyle = this.color
c.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false)
c.stroke()
}
this.update = function() {
if (this.x >= innerWidth - this.radius) {
this.dx = -this.dx
} else if (this.x <= this.radius) {
this.dx = -this.dx
}
if (this.y >= innerHeight - this.radius) {
this.dy = -this.dy
} else if (this.y <= this.radius) {
this.dy = -this.dy
}
this.x += this.dx
this.y += this.dy
this.draw()
}
}
function Rectangle(x, y, dx, dy, height, width, color) {
this.x = x
this.y = y
this.dx = dx
this.dy = dy
this.height = height
this.width = width
this.color = color
this.draw = function() {
c.beginPath()
c.fillStyle = this.color
c.fillRect(this.x, this.y, this.width, this.height)
}
this.update = function() {
if (this.x >= innerWidth - this.width) {
this.dx = -this.dx
} else if (this.x <= 0) {
this.dx = -this.dx
}
if (this.y >= innerHeight - this.height) {
this.dy = -this.dy
} else if (this.y <= 0) {
this.dy = -this.dy
}
this.x += this.dx
this.y += this.dy
this.draw()
}
}
function randSpeed() {
return (Math.random() - 0.5) * 5
}
let rectangleArray = []
let circleArray = []
for (var i = 0; i < 3; i++) {
let heightRect = Math.floor((Math.random() * 100) + 1)
let widthRect = Math.floor((Math.random() * 100) + 1)
rectangleArray.push(new Rectangle(80, 80, randSpeed(), randSpeed(), heightRect, widthRect, random_rgba()))
let radiusCircle = Math.floor((Math.random() * 50) + 1)
circleArray.push(new Circle(80, 80, randSpeed(), randSpeed(), radiusCircle, random_rgba()))
}
function animate() {
requestAnimationFrame(animate)
c.clearRect(0, 0, innerWidth, innerHeight)
for (var i = 0; i < rectangleArray.length; i++) {
rectangleArray[i].draw()
rectangleArray[i].update()
}
for (var i = 0; i < circleArray.length; i++) {
circleArray[i].draw()
circleArray[i].update()
}
}
animate()
<canvas></canvas>

Categories