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

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++;
}
}

Related

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);

React three fiber - Tween Camera

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.

Why does my Animated view not stay in the correct place in React Native?

I created a "circle bar" (group of views) that switch from grey to yellow as the images move. The circles start to transform correctly but then go back to the first spot instead of going to the next circle spot to indict that you are on the next image. The yellow circle just always goes back to the first spot no matter what. Does anyone know why this might be happening?? How do I get it to stay in the next spot?
PLEASE see this video that I made of it: https://youtu.be/BCaSgNexPAs
Here is how I create and handle the circle view transformations:
let circleArray = [];
if (this.state.imgArray) {
this.state.imgArray.forEach((val, i) => {
const scrollCircleVal = this.imgXPos.interpolate({
inputRange: [deviceWidth * (i - 1), deviceWidth * (i + 1)],
outputRange: [-8, 8],
extrapolate: 'clamp',
});
const thisCircle = (
<View
key={'circle' + i}
style={[
styles.track,
{
width: 8,
height: 8,
marginLeft: i === 0 ? 0 : CIRCLE_SPACE,
borderRadius: 75
},
]}
>
<Animated.View
style={[
styles.circle,
{
width: 8,
height: 8,
borderRadius: 75,
transform: [
{translateX: scrollCircleVal},
],
backgroundColor: '#FFD200'
},
]}
/>
</View>
);
circleArray.push(thisCircle)
});
}
And here's my code for how I handle the image swiping:
handleSwipe = (indexDirection) => {
if (!this.state.imgArray[this.state.imgIndex + indexDirection]) {
Animated.spring(this.imgXPos, {
toValue: 0
}).start();
return;
}
this.setState((prevState) => ({
imgIndex: prevState.imgIndex + indexDirection
}), () => {
this.imgXPos.setValue(indexDirection * this.width);
Animated.spring(this.imgXPos, {
toValue: 0
}).start();
});
}
imgPanResponder = PanResponder.create({
onStartShouldSetPanResponder: () => true,
onPanResponderMove: (e, gs) => {
this.imgXPos.setValue(gs.dx);
},
onPanResponderRelease: (e, gs) => {
this.width = Dimensions.get('window').width;
const direction = Math.sign(gs.dx);
if (Math.abs(gs.dx) > this.width * 0.4) {
Animated.timing(this.imgXPos, {
toValue: direction * this.width,
duration: 250
}).start(() => this.handleSwipe(-1 * direction));
} else {
Animated.spring(this.imgXPos, {
toValue: 0
}).start();
}
}
});
Html:
<Animated.Image
{...this.imgPanResponder.panHandlers}
key={'image' + this.state.imgIndex}
style={{left: this.imgXPos, height: '100%', width: '100%', borderRadius: 7}}
resizeMethod={'scale'}
resizeMode={'cover'}
source={{uri: this.state.imgArray[this.state.imgIndex]}}
/>
<View style={styles.circleContainer}>
{circleArray}
</View>
It's hard to get your code at first as it's all in the same spot.
I would first suggest breaking your code into smaller parts: ImageView, CirclesView
Now after we got that done, I would want to try to make the CirclesView a bit simpler (unless you really want this animation view inside the circle).
But from your code, I didn't see the difference for the "selectedImage" (imgIndex)
As it has calculations for each index, but with no reference to the selected image.
Rough ballpark code I would think to do with the current code:
let circleArray = [];
if (this.state.imgArray) {
this.state.imgArray.forEach((val, i) => {
const scrollCircleVal = this.imgXPos.interpolate({
inputRange: [deviceWidth * (i - 1), deviceWidth * (i + 1)],
outputRange: [-8, 8],
extrapolate: 'clamp',
});
const thisCircle = (
<View
key={'circle' + i}
style={[
styles.track,
{
width: 8,
height: 8,
marginLeft: i === 0 ? 0 : CIRCLE_SPACE,
borderRadius: 75
},
]}
>
// LOOK AT THIS LINE BELOW
{this.state.imgIndex == i &&
<Animated.View
style={[
styles.circle,
{
width: 8,
height: 8,
borderRadius: 75,
transform: [
{translateX: scrollCircleVal},
],
backgroundColor: '#FFD200'
},
]}
/>}
</View>
);
circleArray.push(thisCircle)
});
}
checkout the line I added above the "animated" circle for the "selected" circle
I would agree with most of Tzook notices ... but from what I see in code (intentions) all circles are animated (but in fact only one pair affected - one hides, one shows) - animating only selected one doesn't give that.
I animated hundreds 'sliders/galleries' in flash ;) - what with prev/next/neighborh images - shouldn't be animated at the same time?
Images with the same width (or when you can accept margins between them) are easy, you can animate container with 3 (or even only 2) images from longer (looped of course?) list/array. It's like virtual list scrolling.
Having this working circles will be easy, too - animate only 3 of them: prev/curr/next ones.
Simple animations are easy - only swapping images at the end of animation. It could look harder with f.e. bouncing effects (when image slides more/farther than it's target position and next img should be visible for a while) but you can just swap them earlier, just after recognizing direction.

FabricJS and AngularJS – copy and paste object with custom attribute

I'm using some custom attributes while I'm creating my objects. For example in this case "name" and "icon":
$scope.addRoundRect = function () {
var coord = getRandomLeftTop();
var roundrect = (new fabric.Rect({
left: coord.left,
top: coord.top,
fill: '#' + getRandomColor(),
width: 250,
height: 250,
opacity: 1,
scaleX: 1,
scaleY: 1,
angle: 0,
rx: 10,
ry: 10,
strokeWidth: 0,
name: "Rounded Rectangle",
icon: "crop-square"
}));
canvas.add(roundrect).setActiveObject(roundrect);
};
This is my copy/paste function. As you can see I have already tried to paste the relevant attributes – bu I think that they are simply not cloned with the object:
function copy() {
canvas.getActiveObject().clone(function (cloned) {
_clipboard = cloned;
});
}
function paste() {
_clipboard.clone(function (clonedObj) {
canvas.discardActiveObject();
clonedObj.set({
left: clonedObj.left + 10,
top: clonedObj.top + 10,
evented: true,
name: clonedObj.name,
icon: clonedObj.icon,
});
if (clonedObj.type === 'activeSelection') {
clonedObj.canvas = canvas;
clonedObj.forEachObject(function (obj) {
canvas.add(obj);
});
clonedObj.setCoords();
} else {
canvas.add(clonedObj);
}
canvas.setActiveObject(clonedObj);
canvas.requestRenderAll();
});
To make it short: is there a way to clone and paste also this attributes without having to modify the source (ie. impleneting a full fledged custom attribute in the JSO serialization)?
var canvas = new fabric.Canvas('c');
var roundrect = new fabric.Rect({
left: 50,
top: 30,
fill: 'blue',
width: 250,
height: 250,
opacity: 1,
scaleX: 1,
scaleY: 1,
angle: 0,
rx: 10,
ry: 10,
strokeWidth: 0,
name: "Rounded Rectangle",
icon: "crop-square"
});
canvas.add(roundrect).setActiveObject(roundrect);
var customProperties = 'name icon'.split(' ');
function copy() {
canvas.getActiveObject().clone(function(cloned) {
console.log(cloned);
_clipboard = cloned;
}, customProperties);
}
function paste() {
// clone again, so you can do multiple copies.
_clipboard.clone(function(clonedObj) {
canvas.discardActiveObject();
clonedObj.set({
left: clonedObj.left + 10,
top: clonedObj.top + 10,
evented: true,
});
if (clonedObj.type === 'activeSelection') {
// active selection needs a reference to the canvas.
clonedObj.canvas = canvas;
clonedObj.forEachObject(function (obj) {
canvas.add(obj);
});
// this should solve the unselectability
clonedObj.setCoords();
} else {
canvas.add(clonedObj);
}
canvas.setActiveObject(clonedObj);
canvas.requestRenderAll();
console.log(clonedObj);
_clipboard = clonedObj;
},customProperties);
}
canvas {
border: blue dotted 2px;
}
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.min.js"></script>
<button onclick='copy()'>copy</button>
<button onclick='paste()'>paste</button><br>
<canvas id="c" width="400" height="400"></canvas>
object.clone accepts callback function and any additional property you want to include as another parameter. You can send your name and icon as properties to include.
And in paste you no need to clone that object if you are doing so, make sure there also send you are including your additional properties.

How to customize tooltip for forceDirectedGraph in angular nvd3

I am using the force directed graph in angular nv3d. I would like to customize the text color on the nodes as well as modify the tool tip. Ive also been trying to figure out how to force the nodes to be more sparse. Here is my chart object:
chart: {
type: 'forceDirectedGraph',
height: 450,
color: function(d) {
return color(d.Name);
},
tooltipContent: function (key) {
return '<h3>' + key + '</h3>';
},
margin: {top: 20, right: 20, bottom: 20, left: 20},
nodeExtras: function(node) {
node && node
.append('text')
.attr('dx', 15)
.attr('dy', '.35em')
.text(function(d) {
return d.Name;
})
.style('font-size', '25px');
},
},
};
As you can see, I tried adding the tooltipContent property to the chart object to no avail. Any help would be greatly appreciated, thanks!
To customize the tool tip do the following
chart: {
type: 'forceDirectedGraph',
... /* All properties */
height : 400,
tooltip : {
contentGenerator : function (obj) { return "<div> **custom formating** </div>"}
}
}

Resources