React three fiber - Tween Camera - reactjs

I want to tween my camera, from Position A to B. I did it a few times using react spring with a little workaround:
import { useSpring } from "react-spring/three";
const springProps = useSpring({
config: { duration: 1000, easing: easings.easeCubicInOut },
to: {
position: props.position,
lookAt: props.lookAt,
offset: props.offset,
},
onRest: (ya) => {
if (props.enableOrbit) {
props.parentStateModifier({ enableOrbit: true });
}
},
});
useFrame(({ clock, camera, mouse }) => {
camera.position.x = springProps.position.payload[0].value;
camera.position.y = springProps.position.payload[1].value;
camera.position.z = springProps.position.payload[2].value;
camera.lookAt(
springProps.lookAt.payload[0].value,
springProps.lookAt.payload[1].value,
springProps.lookAt.payload[2].value
);
camera.updateProjectionMatrix();
});
This was'nt a very good approach, but it worked.
I am now using #react-spring/three and its not working anymore. "payload" is undefined now and I was able to get the coordinates by calling springProps.x.animation.values[0]._value
But values is empty when not animating. I'm sure there must be a better way to animate camera.
I love react spring for animating three meshes. I hope I can use it for my camera as well.

Ok, I managed to update my code so that my camera is animating again:
const { gl, camera } = useThree();
const springProps = useSpring({
config: { duration: 1000, easing: easings.easeCubic },
from: {
x: - 0.1,
y: - 0.1,
z: - 0.1,
lookAtX: camera.lookAt.x - 0.1,
lookAtY: camera.lookAt.y - 0.1,
lookAtZ: camera.lookAt.z - 0.1,
},
to: {
x: cameraData.position[0],
y: cameraData.position[1],
z: cameraData.position[2],
lookAtX: cameraData.lookAt[0],
lookAtY: cameraData.lookAt[1],
lookAtZ: cameraData.lookAt[2],
}
});
useFrame((state, delta) => {
if (!orbit) {
camera.position.x = springProps.x.animation.values[0]._value;
camera.position.y = springProps.y.animation.values[0]._value;
camera.position.z = springProps.z.animation.values[0]._value;
camera.lookAt(
springProps.lookAtX.animation.values[0]._value,
springProps.lookAtY.animation.values[0]._value,
springProps.lookAtZ.animation.values[0]._value
);
}
});
Problem is, that if the from and to values are the same, values[0] will be undefined. So for example this will not work with my code:
from: {
x: 0
y: 0,
z: 0,
},
to: {
x: 0,
y: 2,
z: 4,
}
because x has the same value. I hope someone can provide a better way of animating cameras in r3f.

Related

The app gets slower with every change in props [duplicate]

This question already has an answer here:
React won't draw anything in the canvas in useEffect
(1 answer)
Closed 16 days ago.
I use Matter js for physics and canvas for rendering 100 items, after every change in props the app gets slower and slower. At the same time, subsequent downloads with the same props occur instantly, i.e. past images and elements remained and were not deleted, which loads the application.
enter image description here
"Top" dropdown menu changes props for bubbles component, code:
const Bubbles = ({ coins }) => {
var winwidth = window.innerWidth;
var winheight = window.innerHeight - 80;
const [physics, setPhysics] = useState({
frictionAir: 0,
friction: 0.2,
frictionStatic: 0.2,
restitution: 0.1,
inertia: Infinity,
density: 0.8,
});
useEffect(() => {
setSize(coins);
// create an engine
const engine = Engine.create();
const world = engine.world;
// create a renderer
const render = Render.create({
element: document.querySelector(".bubbles"),
engine: engine,
options: {
width: winwidth,
height: winheight,
showAngleIndicator: false,
background: "transparent",
wireframeBackground: "transparent",
wireframes: false,
showDebug: false,
},
});
const bubbles = [];
// create a canvas
const canvas = document.createElement("canvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.querySelector(".bubbles").appendChild(canvas);
const ctx = canvas.getContext("2d");
// create 100 random bubbles
for (let i = 0; i < coins.length; i++) {
const x = Math.random() * window.innerWidth;
const y = Math.random() * window.innerHeight;
const bubble = Bodies.circle(x, y, coins[i].size / 2, {
...physics,
render: {
fillStyle: "transparent",
},
});
Composite.add(engine.world, bubble);
// store the bubble and its content data in an object
bubbles.push({
bubble,
content: {
radius: coins[i].radius,
text: `${i + 1}`,
},
});
}
// update the canvas on each engine update
Matter.Events.on(engine, "afterUpdate", function () {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < bubbles.length; i++) {
const bubble = coins[i];
const pos = bubbles[i].bubble.position;
const size = bubble.size;
const text = bubble.symbol;
const priceChange = bubble.price_change_percentage_24h.toFixed(1);
const image = new Image();
image.src = bubble.image;
if (priceChange > 0) {
ctx.fillStyle = "rgba(5, 222, 5, 0.15)";
ctx.strokeStyle = "rgba(5, 222, 5, 0.6)";
} else if (priceChange < 0) {
ctx.fillStyle = "rgba(166, 53, 53, 0.15)";
ctx.strokeStyle = "rgba(166, 53, 53, 0.8)";
} else {
ctx.fillStyle = "rgba(255, 255, 89, 0.069)";
ctx.strokeStyle = "rgba(187, 231, 11, 0.443)";
}
ctx.beginPath();
ctx.arc(pos.x, pos.y, size / 2, 0, 2 * Math.PI);
ctx.fill();
ctx.stroke();
ctx.drawImage(
image,
pos.x - size / 5,
pos.y - size / 2.5,
size / 2.5,
size / 2.5
);
ctx.font = `${size / 6}px Acme`;
ctx.fillStyle = "white";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, pos.x, pos.y + size / 6.5);
ctx.font = `${size / 6.5}px Acme`;
ctx.fillStyle = "white";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(priceChange + "%", pos.x, pos.y + size / 3);
}
});
// fit the render viewport to the scene
window.addEventListener("onload", () => {
Render.lookAt(render, {
min: { x: 0, y: 0 },
max: { x: 100000, y: 10000 },
});
});
// run the engine
Runner.run(engine);
// run the renderer
Render.run(render);
return () => {
// stop the engine and renderer
Engine.clear(engine);
Render.stop(render);
Runner.stop(engine);
// remove the canvas from the DOM
canvas.remove();
};
}, [coins]);
return <></>;
};
export default Bubbles;
after each update of the coins props, I deleted the canvas and stopped the engine, but still the speed worsened
return () => {
// stop the engine and renderer
Engine.clear(engine);
Render.stop(render);
Runner.stop(engine);
// remove the canvas from the DOM
canvas.remove();
};
I want to either stop re-creating the engine and the matter js world, canvas with images.
Only without window.location.reload(), because I need to save props like "Top" and "Earth, Trampoline", etc.
I solved the problem. I didn't properly clear the js canvas value and also didn't set events.off when unmounting the component.
Here is the solution to my problem
return () => {
//set Matter Js events off. drawCanvas - afterUpdate event function
Events.off(engine, 'afterUpdate', drawCanvas);
Render.stop(render);
Composite.clear(engine.world);
Runner.stop(engine)
Engine.clear(engine);
render.canvas.remove();
render.canvas = null;
render.context = null;
// remove the canvas from the DOM
canvas.remove();
};

TradingView - Lightweight charts - Realtime histogram ( volume indicator)

I managed to get the real time example to work:
https://jsfiddle.net/TradingView/yozeu6k1/
I tried to get a real time histogram underneath, as the usual volume indicator and the behavior is random.
A snapshot of the chart:
enter image description here
As we can see the starting point of those bars differ one from another.
Series definition:
const volumeSeries = chart.addHistogramSeries({
priceFormat: {
type: 'volume',
},
priceScaleId: '',
scaleMargins: {
top: 0.8,
bottom: 0,
}
});
Update:
volumeSeries.update({
time: data.time,
value: data.volume
});
Can anyone point me to an example in order to get a candlestick chart with a volume indicator to work? Both updating in real time.
I got it to work, basically the issue was that the histogram understands negative values as a down facing bar, so in order to show a volume indicator we have to show the absolute value of the volume and change the color.
A working example at: https://jsfiddle.net/rondolfo/0zg7u9tv/57/
//colours
var green = 'rgb(38,166,154)';
var red = 'rgb(255,82,82)';
var black = '#000000';
var white = 'rgba(255, 255, 255, 0.9)';
var grey = 'rgba(42, 46, 57, 0.5)';
// chart definition
var chart = LightweightCharts.createChart(document.body, {
width: 800,
height: 400,
layout: {
backgroundColor: black,
textColor: white,
},
grid: {
vertLines: {
visible: false,
},
horzLines: {
color: grey,
},
},
crosshair: {
mode: LightweightCharts.CrosshairMode.Normal,
}
});
chart.applyOptions({
timeScale: {
borderVisible: false,
borderColor: '#fff000',
visible: true,
timeVisible: true,
minBarSpacing: 0.0,
}
});
const candleStickSeries = chart.addCandlestickSeries({
upColor: green,
downColor: red,
wickUpColor: green,
wickDownColor: red,
borderVisible: false,
priceLineVisible: false,
});
const volumeSeries = chart.addHistogramSeries({
priceFormat: {
type: 'volume',
},
priceScaleId: '',
scaleMargins: {
top: 0.8,
bottom: 0.02,
}
});
//end chart definition
//data loading
jQuery.ajaxSetup({
async: false
});
var url = 'https://raw.githubusercontent.com/AnAlgoTrader/TradingView.LightWeightCharts.Example/main/InputData/prices.json';
var data = [];
$.get(url, function(result) {
data = JSON.parse(result);
});
//end data loading
//real time updates
var index = 0;
setInterval(function() {
if (index > data.length) return;
var item = data[index];
candleStickSeries.update({
time: item.time,
open: item.open,
high: item.high,
low: item.low,
close: item.close
});
var volumeColour = item.volume < 0 ? red : green;
volumeSeries.update({
time: item.time,
value: Math.abs(item.volume),
color: volumeColour
});
index++;
}, 1000);

Give different colors to area under and over a specific point on a D3 line chart

I've recently started working with D3 and I am moving all my existing charts over from Chartjs and so far my attempts have been successful. There is this one chart however that I am unable to produce exactly the same way in D3.
So with Chartjs, there's properties built in to the library that we can use to set the colors for values above and below a certain point on a Line chart. Here's what I had used to get the intended chart with Chartjs:
...config,
fill: {
above: '#4E4AFF20',
below: '#FF515114',
target: 'origin'
},
...config
And this is what the chart in Chartjs ended up looking like:
But D3 doesn't seem to have such a thing as far as I can tell. There's only gradients. So here's what I was able to build in D3:
As you can see, this looks way different from what I had earlier with Chartjs. Also notice how the gradient exists in both the line and the colored area underneath. I know it's there because I added it but that's not what I want and everywhere I look, that's the only way people are doing it. I have done countless attempts to fix this to no avail hence now I'm here asking for your help. Here's the D3 code I have right now:
import * as d3 from 'd3';
import { useEffect, useRef } from 'react';
interface Data {
x: number;
y: number;
}
const width = 350;
const height = 117;
const zeroPoint = 0;
const data: Data[] = [
{ x: 0, y: -20 },
{ x: 10, y: -20 },
{ x: 20, y: -20 },
{ x: 40, y: -20 },
{ x: 50, y: -20 },
{ x: 60, y: -20 },
{ x: 70, y: -20 },
{ x: 80, y: 0 },
{ x: 90, y: 20 },
{ x: 100, y: 20 },
{ x: 110, y: 20 },
{ x: 120, y: 20 },
{ x: 130, y: 20 },
{ x: 140, y: 20 },
{ x: 150, y: 20 }
];
export const Chart: React.FC = () => {
const ref = useRef<SVGSVGElement>(null);
const generateLinePath = (
element: d3.Selection<SVGSVGElement, unknown, null, undefined>,
data: Data[],
xScale: d3.ScaleLinear<number, number>,
yScale: d3.ScaleLinear<number, number>
) => {
const lineGenerator = d3
.line<Data>()
.x(d => xScale(d.x))
.y(d => yScale(d.y));
element.append('path').attr('d', lineGenerator(data));
};
const drawZeroLine = (element: d3.Selection<SVGSVGElement, unknown, null, undefined>, yScale: d3.ScaleLinear<number, number>) => {
element
.append('line')
.attr('x1', '0')
.attr('y1', yScale(zeroPoint))
.attr('x2', width)
.attr('y2', yScale(zeroPoint))
.attr('stroke', '#c4c4c4');
};
const createChart = (data: Data[]) => {
const svg = d3.select(ref.current!).attr('viewBox', `0 0 ${width} ${height}`);
svg.selectAll('*').remove();
const [minX, maxX] = d3.extent(data, d => d.x);
const [minY, maxY] = d3.extent(data, d => d.y);
const xScale = d3.scaleLinear().domain([minX!, maxX!]).range([0, width]);
const yScale = d3
.scaleLinear()
.domain([minY!, maxY!])
.range([height, 0]);
svg
.append('linearGradient')
.attr('id', 'line-gradient')
.attr('gradientUnits', 'userSpaceOnUse')
.attr('x1', 0)
.attr('x2', width)
.selectAll('stop')
.data(data)
.join('stop')
.attr('offset', d => xScale(d.x) / width)
.attr('stop-color', d => (d.y < zeroPoint ? '#FF5151' : '#4E4AFF'));
svg
.append('linearGradient')
.attr('id', 'area-gradient')
.attr('gradientUnits', 'userSpaceOnUse')
.attr('x1', xScale(data[0].x))
.attr('x2', xScale(data[data.length - 1].x))
.selectAll('stop')
.data([
{ color: '#FF515110', offset: '0%' },
{ color: '#4E4AFF20', offset: '100%' }
])
.enter()
.append('stop')
.attr('offset', function (d) {
return d.offset;
})
.attr('stop-color', function (d) {
return d.color;
});
svg.attr('stroke', 'url(#line-gradient)').attr('fill', 'url(#area-gradient)');
generateLinePath(svg, data, xScale, yScale);
drawZeroLine(svg, yScale);
};
useEffect(() => {
createChart(data);
}, []);
return <svg ref={ref} />;
};
So there's two problems I am looking to get solved with your help. The more important one is to give different colors to areas under and above the zero line in D3 the way I was able to do with Chartjs and the other one is moving away from gradients and get solid colors without any smooth transitions on both the line and the colored areas underneath.
Alright I managed to recreate the same chart in D3 using a workaround.
So it's not as straightforward as it's in Chartjs but it works pretty well. The idea is to create polygons under and over the line using the same data used to generate the line.
So my chart works like this. The grey line is a straight zero line and the values below zero go under that line with a red color and the ones above are purple. And here's what the Chart data looks like:
data = [
{ x: 0, y: 0 },
{ x: 1, y: 1 },
...
]
Anyways, here's the steps
Generate the scales
const [minX, maxX] = d3.extent(data, d => d.x);
const [minY, maxY] = d3.extent(data, d => d.y);
const xScale = d3.scaleLinear().domain([minX, maxX]).range([0, width]);
const yScale = d3.scaleLinear().domain([minY, maxY]).range([height, 0]);
Generate the line chart using D3's line() function. And don't give any stroke to the generated line.
const lineGenerator = d3.line().x(d => xScale(d.x)).y(d => yScale(d.y));
element.append('path').attr('d', lineGenerator(data));
Add a red SVG polygon that starts from the left side at zero line, then goes to the left bottom, then to where the value starts becoming negative and then finally to where the line reaches the zero line again.
svg.append('polygon').attr(
'points',
`
${xScale(minX - 1)},${yScale(0)} // top left point
${xScale(minX - 1)},${yScale(minY)} // bottom left point
${xScale(data[indexWhereRedPointStartsBecomingPositive].x)},${yScale(data[indexWhereRedPointStartsBecomingPositive].y)} // bottom right point
${xScale(data[indexWhereXReachesZeroLine].x)},${yScale(0)} // top right point
`
)
.attr('fill', 'lightRed')
.attr('stroke', 'darkRed');
Notice how we gave the red stroke to the polygon? That's the reason why we got rid of the stroke from the line and gave it here instead. This is because we need two separate colors (red for below and purple for above) for the chart. The reason why we do minX - 1 is because the stroke is applied to all four sides of the polygon and we want to hide it from the left side so we subtract 1px from the left.
Add another purple SVG polygon that starts from the left side at zero line (where the purple area starts somewhere in the middle), then goes all the way to the right end of the chart and then goes up to the top.
svg.append('polygon').attr(
'points',
`
${xScale(data[indexWhereValueStartsGoingPositive].x)},${yScale(0)}
${width + 1},${yScale(data[data.length - 1].y)}
${width + 1},${yScale(0)}
`
)
.attr('fill', 'lightPurple')
.attr('stroke', 'darkPurple');
Here we do width + 1 to hide the stroke of this purple polygon on the right side the same way we did minX - 1 with the left side of the red box.
So in conclusion, instead of giving stroke to the line generated using d3.line(), give strokes to the two polygons created using the same data that was used to generate the line chart and create the polygons 1px larger than the chart data so the strokes don't appear on the left and right side of the charts.
That's quite a lot I know but I couldn't think of any other way to get the chart to look like this. Anyways, I hope this helps anyone else experiencing a similar problem.

Animating elements with react-spring usesprings hook

Trying to animate a bunch of objects to their positions, and useSpring works for me (for single element), but useSprings is not for 3 objects.
Here is demo (mousedown red ball):
https://codesandbox.io/s/try-to-do-zgit5?file=/src/App.js:1254-1857
Here is code:
// working for me
const { z } = useSpring({
from: { z: 0 },
to: { z: mousedown ? 0 : -0.5 }
})
// not working with state change
// although working with a
// loop: { reverse: true, delay: 0 },
// but not accounting state changes
const [springs] = useSprings(3, (i) => ({
from: { x: 0, y: i * 2 - 2 },
to: { x: mousedown ? 0.5 : -0.5, y: i * 2 - 2 + 1 },
}))
and the elements:
// works
<a.mesh position-z={z}
onPointerDown={(e) => setMousedown(true)}
onPointerUp={(e) => setMousedown(false)}>...</a.mesh>
// not changing positions with state
{springs.map(({ x, y }, index) => (
<a.mesh position-x={x} position-y={y} key={`0${index}`}>...</a.mesh>
))}
As im new to react-spring, this might be a ridiculous simple problem, but im just stuck with this myself now
Solved thanx to Paul Henschel in this sandbox https://codesandbox.io/s/try-to-do-forked-gwy21?file=/src/App.js , addition of [mousedown] dependency parameter to useSprings hook was needed.

Chartist graphs get re-drawn everytime I click on any button or resize window

I really like this library, but I can't seem to control this issue somehow. If any event occurs the graphs are being re-drawn every time.
I am using React.js and this is how I am creating and displaying the Chartist graphs:
const dailyComplaintsChart = {
data: {
labels: ["M", "T", "W", "T", "F", "S", "S"],
series: [whichType.seriesDaily]
},
options: {
lineSmooth: Chartist.Interpolation.cardinal({
tension: 0
}),
low: 0,
high: highestValue.highestValueDaily, // creative tim: we recommend you to set the high sa the biggest value + something for a better look
chartPadding: {
top: 0,
right: 0,
bottom: 0,
left: 0
}
},
// for animation
animation: {
draw: function (data) {
if (data.type === "line" || data.type === "area") {
data.element.animate({
d: {
begin: 600,
dur: 700,
from: data.path
.clone()
.scale(1, 0)
.translate(0, data.chartRect.height())
.stringify(),
to: data.path.clone().stringify(),
easing: Chartist.Svg.Easing.easeOutQuint
}
});
} else if (data.type === "point") {
data.element.animate({
opacity: {
begin: (data.index + 1) * delays,
dur: durations,
from: 0,
to: 1,
easing: "ease"
}
});
}
}
}
};
return(
<div className="daily-graph">
<ChartistGraph
className="ct-chart-background-daily-complaints"
data={dailyComplaintsChart.data}
type="Line"
options={dailyComplaintsChart.options}
listener={dailyComplaintsChart.animation}
/>
<div className={classes.line}>
<p>Daily Complaints</p>
</div>
</div>
)
This problem is caused by the use of animation, So you have to put all the animate function in an if statement and set a counter outside of draw function.
let animated = 0;
draw(data) {
if (animated <= label.length) {
// animate
data.element.animate(...)
animated++;
}
}

Resources