Optimizing updating many elements continuously with react - javascript

This is my first time working with react, and i tried to create an animated background. I did this by creating a large amount of divs, and updating their position every time a timer ticks.
moveCircles() {
let tempCircles = this.state.bgCircles;
for (let i = 0; i < amount; i++) {
tempCircles[i].left = this.state.bgCircles[i].left + Math.cos(this.state.bgCircles[i].angle) * 2;
tempCircles[i].top = this.state.bgCircles[i].top + Math.sin(this.state.bgCircles[i].angle) * 2;
if (tempCircles[i].top < (0 - tempCircles[i].radius)) {
tempCircles[i].top = totalHeight;
} else if(tempCircles[i].top > totalHeight) {
tempCircles[i].top = 0 - tempCircles[i].radius
}
if (tempCircles[i].left < (0 - tempCircles[i].radius)) {
tempCircles[i].left = totalWidth;
} else if (tempCircles[i].left > totalWidth) {
tempCircles[i].left = 0 - tempCircles[i].radius;
}
}
this.setState({
bgCircles: tempCircles,
initialized: true
});
}
However, this is (unsurprisingly) not very optimized, and can get a bit laggy.
My latest try looks like this: https://codepen.io/Miasha/pen/XWqZVeV
Is there a more optimized way of achieving this?

Related

Executing function once in a game loop

I have a game loop that refreshes ~20 times per second with the following condition, inside function growPlayerBlockCounterWinner():
if (obstacleArray[i][2] > canvas.height) {player.size += 5;}
That means: if black object goes outside the canvas area, player size will increase by 5 pixels.
The function normally executes once, but due to putting it in a game loop, it executes each time the game is refreshed, so player is growing continuously.
Previously i had it with the sign '=' instead od '>', but that was working well when black blocks were moving pixel by pixel and i want them to move faster.
You can inspect the problem and full code on the remote server: https://stacho163.000webhostapp.com/firstLevel.html
Below I paste only my obstacle functions:
// js game script //
let obstacle = {
size: 0,
posX: 0,
posY: 0,
speed: 0
}
let obstacleArray = new Array(100);
function generateObstacle() {
for (i = 0; i < obstacleArray.length; i++) {
obstacle.size = Math.round((Math.random() * 100) + 50);
obstacle.posX = Math.round((Math.random() * (canvas.width -
obstacle.size)));
obstacle.posY = -450 - (i * 100);
obstacle.speed = 5;
obstacleArray[i] = [obstacle.size, obstacle.posX, obstacle.posY,
obstacle.speed];
}
}
function drawObstacle() {
for (i = 0; i < obstacleArray.length; i++) {
ctx.fillStyle = "#000";
ctx.fillRect(obstacleArray[i][1], obstacleArray[i][2],
obstacleArray[i][0], obstacleArray[i][0]);
obstacleArray[i][2] += obstacleArray[i][3];
}
}
function growPlayerBlockCounterWinner() {
for (i = 0; i < obstacleArray.length; i++) {
// grow player
if (obstacleArray[i][2] > canvas.height) {
player.size += 5;
}
}
}
generateObstacle();
function game() {
drawObstacle();
growPlayerBlockCounterWinner();
requestAnimationFrame(game);
}
requestAnimationFrame(game);
I am looking for opinions, maybe my logic about that statement is incorrect or i should place that statement in other place.
Thanks for your tips :)
As you have a defined number of black boxes, you might be able to store, for which black box the player already increased size like this:
let obstacle = {...};
var affectedBlackBoxes = {};
//...//
function growPlayerBlockCounterWinner() {
for (i = 0; i < obstacleArray.length; i++) {
// grow player
if (obstacleArray[i][2] > canvas.height && !affectedBlackBoxes[i]) {
player.size += 5;
affectedBlackBoxes[i] = true;
}
}
}

Svg object modified with setAttributeNS not updating until after while loop

I'm creating a small game in javascript and I'm using svg for the graphics. Right now I'm having a problem with updating the game in the middle of a game tick. If I exit my loop directly after I update the fill attribute with "setAttributeNS", it's redrawn, but if I don't do that, it isn't updated until after "game_tick" is over. Even worse, if I call "game_tick" multiple times in a row, the svg objects aren't updated until after I've run all of the "game_tick"s instead of being updated after each one.
function game_tick(){
num_grid_copy = num_grid.slice();
for (var x = 0; x < num_squares_x; x += 1) {
for (var y = 0; y < num_squares_x; y += 1) {
var n = get_neighbors(x,y);
var isAliveInNextGen = next_gen(n, num_grid[x*num_squares_x+y]);
num_grid_copy[x*num_squares_x+y] = isAliveInNextGen;
if (isAliveInNextGen == 1){
rect_grid[x*num_squares_x+y].setAttributeNS(null, 'fill', '#0099ff');
}
else {
rect_grid[x*num_squares_x+y].setAttributeNS(null, 'fill', '#fff');
}
}
}
num_grid = num_grid_copy;
}
Thanks to valuable input from Robert I realized that javascript execution and page rendering are done in the same thread. I changed the function to the following:
function start() {
var inc = 0,
max = 25;
delay = 100; // 100 milliseconds
var repeat = setInterval(function() {
game_tick();
if (++inc >= max)
clearInterval(repeat);
},
delay);
}
This works fine. I can set the delay and the number of times it repeats.

Why doesn't my requestAnimation with setTimeout functions work in Chrome/Opera?

I'm trying to make an animated gallery that will smoothly paint first slide, then wait for a while and then repaint the next one and so on (slides are painted by pieces).
I used for that requestAnimationFrame captured in setTimeout and it works just as I want, but only in Firefox. It doesn't invoke the animation at all in Chrome or Opera.
I've tried to comment out the whole part that animates the slide (so that only the first part of it would be painted), but it didn't help. Tried also to take away all that part that is cutting the canvas and image on parts and just paint a whole image, but it didn't help too.
Here's a jsfiddle https://jsfiddle.net/Valilna/64qmtpvu/3/
var slideW = slideObjectsArray[j].width;
var slideH = (slideW / sectionCountW) * sectionCountH;
var slideSectorW = slideW / 5;
var gallerySectorW = galleryWidth / 5;
var speedGallery = (gallerySectorW/100) * 5;
var speedSlide = (slideSectorW/100)*5;
function drawSlide () {
for (n = 0; n < 5; n++) {
if (speedGallery <= gallerySectorW) {
ctx.drawImage(slideObjectsArray[j], slideSectorW * n, 0,
speedSlide, slideH,
(gallerySectorW * (n + 1) - speedGallery),
0, speedGallery, galleryHeight);
} else if (speedGallery > gallerySectorW){
speedGallery = gallerySectorW;
ctx.drawImage(slideObjectsArray[j], slideSectorW * n, 0,
speedSlide, slideH,
(gallerySectorW * (n + 1) - speedGallery),
0, speedGallery, galleryHeight);
}
}
if (speedGallery < gallerySectorW) {
speedGallery += (gallerySectorW/100) * 5;
speedSlide += (slideSectorW/100)*5;
setTimeout(function () {
requestAnimationFrame(drawSlide);
}, 25);
} else if (speedGallery === gallerySectorW) {
speedGallery = (gallerySectorW/100) * 5;
speedSlide = (slideSectorW/100)*5;
if (j < 6){
j ++;
} else {
j = 0;
}
setTimeout(function () {
requestAnimationFrame(drawSlide);
}, 4000);
}
}
slideObjectsArray[0].onload = drawSlide;
I'm new to coding and just started to study, so I'm sure I've made some stupid mistake and I would be very grateful if you'll show it to me.

Creating a slider between two numbers

So I've been working on re-producing the slider found here https://www.skylight.io/ ( Scroll down to find the price slider ).
So far Ive managed to create something similiar, but some numbers are hard coded, making it difficult to change and not very re-usable.
I've been researching around and I think I need to use Math.log() and Math.exp() together to achieve something like in the link above but I'm not sure.
Heres a jsfiddle of what I have so far https://jsfiddle.net/7wrvpb34/.
I feel that its the maths part of this problem that is halting me I think, so any help would be greatly appreciated.
Javascript code below:
var slider = document.getElementById("slider")
var sliderFill = document.getElementById("slider-fill")
var knob = document.getElementById("knob")
var mouseDown;
var mousePos = {x:0};
var knobPosition;
var minPrice = 20;
var price = 0;
var minRequests = 50;
var requests = 50 + ",000";
var incrementSpeed = 2;
var incrementModifier = 20;
var incrementValue = 1;
var minMillionCount = 1;
var millionCount = 1;
var previousRequestAmount = 0;
document.getElementById("price").innerHTML = price;
document.getElementById("requests").innerHTML = requests;
highlightTable(1);
document.addEventListener('mousemove', function(e) {
if(mouseDown) {
updateSlider(e);
}
})
function updateSlider(event) {
mousePos.x = event.clientX - slider.getBoundingClientRect().left;
mousePos.x -= knob.offsetWidth / 2;
console.log(mousePos.x);
if(mousePos.x < 0) {
knob.style.left = "0px";
sliderFill.style.width = "0px";
price = 0;
requests = 50 + ",000";
document.getElementById("price").innerHTML = price;
document.getElementById("requests").innerHTML = requests;
return
}
if(mousePos.x > slider.offsetWidth - 20) {
return
}
sliderFill.style.width = mousePos.x + 10 + "px";
knob.style.left = mousePos.x + "px";
//Increase requests by using X position of mouse
incrementSpeed = mousePos.x / incrementModifier;
requests = minRequests + (mousePos.x * incrementSpeed);
//Round to nearest 1
requests = Math.round(requests / incrementValue) * incrementValue;
if (requests >= 1000){
var m = requests/ 1000;
m = Math.round(m / 1) * 1;
//Problem, lower the modifier depending on requests
incrementModifier = 20 * 0.95;
document.getElementById("requests").innerHTML = m + " million";
//Adjust Prices
if(( requests >= 1000) && (requests < 10000)) {
var numOfMillions = requests / 100;
//Round to closest 10.
//10 * number of millions
var rounded = Math.round(numOfMillions / 10) * 10;
price = minPrice + rounded;
highlightTable(3);
}
//Adjust Prices
if(requests >= 10000) {
var numOfMillions = requests / 1000;
var rounded = Math.round(numOfMillions / 1) * 1;
var basePrice = minPrice * 6;
price = basePrice + rounded;
highlightTable(4);
}
} else {
incrementModifier = 20;
document.getElementById("requests").innerHTML = requests + ",000"
if(requests < 100) {
highlightTable(1);
price = 0;
} else {
highlightTable(2);
price = 20;
}
}
previousRequestAmount = requests;
document.getElementById("price").innerHTML = price;
}
knob.addEventListener('mousedown', function() {
mouseDown = true;
});
document.addEventListener('mouseup', function() {
mouseDown = false;
});
function highlightTable(rowNum) {
var table = document.getElementById("payment-table")
for(var i = 0; i < table.rows.length; ++i) {
var row = table.rows[i]
if(i == rowNum) {
row.style.background = "grey"
} else {
row.style.background = "white";
}
}
}
Thank you for your time.
If you want it to be reusable you need to create a mathematical function that assigns a result to the number of requests. I will give you a very easy example.
If you want a different result for 1,10,100,100,10000 etc
var d = Math.log10(requests);
if(d<1){
doSomething();
}else if(d<2){
doSomethingElse();
} //etc
This way if you want to change the specific values that create certain results, all you need to do is change the function.
This only works if your tiers of requests follow a math function, if they don't you need to hard code it.
However if say they don't follow a math function, but you know how you would like them to change based on a value then you can do this.
var changingValue = 4;
if(requests < 400*changingValue){
doSomthing();
}else if(requests <= 400*changingValue*changingValue){
doSomethingElse();
}else{// the requests is greater than any of the above
doTheOtherThing();
}
Edit:
For the second one you need to make sure that each condition if always larger than the other from top to bottom.
The description "increasingly increasing" matches an arbitrary number of functions. I assume you also want it to be continuous, since you already have a non-continuous solution.
TL;DR
Use an exponential function.
Generic approach
Assuming imin and imax are the minimal and maximal values of the slider (i for input) and omin and omax are the minimal and maximal values to be displayed, the simplest thing I can think of would be a multiplication by something based on the input value:
f(x)
{
return omin + (omax - omin) * g((x - imin) / (imax - imin));
}
This will pass 0 to g if x == imin and 1 if x == imax.
The return value r of g(y) should be
r == 0 for y == 0
r == 1 for y == 1
0 < r < y for 0 < y < 1
The simplest function that I can think of that fulfills this is an exponential function with exponent > 1.
An exponent of 1 would be a linear function.
An exponent of 2 would be make the middle of the slider display one fourth of the maximum price instead of half of it.
But you really need to find that exponent yourself, based on your needs.

setting a time delay between two frame when animation a sprite sheet

This is my jsfiddle :http://jsfiddle.net/Z7a5h/
As you can see the animation of the sprite sheet when the player is not moving is too fast so I was trying to make it slow by declaring two variable lastRenderTime: 0,RenderRate: 50000
but my code is not working and it seem I have a misunderstanding of the algorithm I am using so can anyone lay me a hand to how can I fix it?
if (!this.IsWaiting) {
this.IsWaiting = true;
this.Pos = 1 + (this.Pos + 1) % 3;
}
else {
var now = Date.now();
if (now - this.lastRenderTime < this.RenderRate) this.IsWaiting = false;
this.lastRenderTime = now;
}
Yes, your logic is wrong. You were using the wrong operator < instead of >. Also, you needed to update the lastRenderTime only when the condition is statisfied, otherwise it keeps getting updated and the value of now - this.lastRenderTime never ends up becoming more than 20 or so.
if (!this.IsWaiting) {
this.IsWaiting = true;
this.Pos = 1 + (this.Pos + 1) % 3;
}
else {
var now = Date.now();
if (now - this.lastRenderTime > this.RenderRate) {
this.IsWaiting = false;
this.lastRenderTime = now;
}
}
Here is your updated fiddle.

Categories

Resources