zoomband is displayed as lineseries when i add a stepseries to a chartXY? - lightningchart

i find that zoombandchart is displayed as lineseries when i add a stepseries to a chartXY,
what i expected is that the series in zoombandchart as stepseries, which is same as in chart,
so how to fixed this problem? here is my code:
const {
lightningChart,
StepOptions,
UILayoutBuilders,
UIElementBuilders,
UIButtonPictures,
UIBackgrounds,
UIOrigins,
emptyFill,
emptyLine,
AxisTickStrategies,
SolidFill,
Themes,
createProgressiveTraceGenerator
} = lcjs
const dashboard = lightningChart().Dashboard( {
numberOfColumns: 1,
numberOfRows: 4
} )
const chart = dashboard.createChartXY( {
columnIndex: 0,
columnSpan: 1,
rowIndex: 0,
rowSpan: 3
})
const zoomBandChart = dashboard.createZoomBandChart({
columnIndex: 0,
columnSpan: 1,
rowIndex: 3,
rowSpan: 1,
axis: chart.getDefaultAxisX()
})
zoomBandChart
.setTitleFillStyle(emptyFill)
zoomBandChart.getDefaultAxisX()
.setTickStrategy( AxisTickStrategies.Empty )
zoomBandChart.getDefaultAxisY()
.setAnimationScroll(false)
const line = chart.addStepSeries({mode:StepOptions.after})
line.add([
{x:0,y:1},
{x:1,y:0},
{x:2,y:1},
{x:3,y:1},
{x:4,y:1},
{x:5,y:1},
{x:6,y:1},
])
<script src="https://unpkg.com/#arction/lcjs#2.1.0/dist/lcjs.iife.js"></script>

Related

How to exclude code from running inside requestAnimationFrame

Hi all, in a nextjs app Im using requestAnimationFrame and matter.js to animate shapes created using paper.js. The shapes are created with a javascript Class inside a forEach loop. Each shape (RegularPolygon) has a random number of sides. When I run the code, Matter.js takes care of the physics but the logic to create the random sides also animates creating a cool (but undesirable strobing effect) of continuously randomising the number of sides of the RegularPolygon. I'm looking for a way of creating the shapes with random sides, once, and then animating them. Thanks in advance.
link to netlify site
import { Engine, Render, World, Bodies } from 'matter-js';
import { useEffect, useRef } from 'react';
import { paper } from 'paper';
const random = (min, max) => {
return Math.random() * min + Math.random() * max + min;
};
function Canvas(props) {
const scene = useRef();
const engine = useRef(Engine.create());
const paperRef = useRef();
const raf = useRef();
console.log(random);
useEffect(() => {
const time = 0;
window.addEventListener('load', () => {
paper.setup(paperRef.current);
const cw = document.body.clientWidth;
const ch = document.body.clientHeight;
const render = Render.create({
element: scene.current,
engine: engine.current,
options: {
width: cw,
height: ch,
wireframes: false,
background: 'transparent',
},
});
World.add(engine.current.world, [
Bodies.rectangle(cw / 2, -10, cw, 20, {
isStatic: true,
}),
Bodies.rectangle(-10, ch / 2, 20, ch, {
isStatic: true,
fillStyle: '#F35e66',
}),
Bodies.rectangle(cw / 2, ch + 10, cw, 20, {
isStatic: true,
fillStyle: '#F35e66',
}),
Bodies.rectangle(cw + 10, ch / 2, 20, ch, {
isStatic: true,
fillStyle: '#F35e66',
}),
]);
Engine.run(engine.current);
Render.run(render);
const balls = [];
for (let i = 0; i < 40; i++) {
balls.push(
Bodies.circle(Math.random() * cw, 0, 80, {
density: Math.random(),
friction: 0.01,
frictionAir: 0.00001,
restitution: 0.8,
render: {
fillStyle: '#F35e66',
strokeStyle: 'black',
lineWidth: 1,
},
})
);
}
var ball = Bodies.circle(0, 0, 20, {
density: 0.04,
friction: 0.01,
frictionAir: 0.00001,
restitution: 0.8,
render: {
fillStyle: '#F35e66',
strokeStyle: 'black',
lineWidth: 1,
},
});
for (let i = 0; i < balls.length; i++) {
World.add(engine.current.world, [balls[i]]);
}
const shapes = [];
for (let i = 0; i < balls.length; i++) {
shapes.push(
new paper.Path.RegularPolygon({
position: new paper.Point([
balls[i].position.x,
balls[i].position.y,
]),
sides: Math.floor(random(0, 8)),
radius: 100,
fillColor: 'tomato',
})
);
}
class Shape {
constructor(x, y, angle) {
this.angle = angle;
this.x = x;
this.y = y;
this.draw();
this.shape = new paper.Path.RegularPolygon({
position: new paper.Point([this.x, this.y]),
sides: Math.floor(random(0, 8)),
radius: 100,
fillColor: 'tomato',
});
}
draw() {
// this.shape.rotate(this.angle);
}
}
console.log(ball);
const callback = () => {
// paper.view.update();
paper.project.clear();
balls.forEach((ball) => {
new Shape(ball.position.x, ball.position.y, ball.angle);
// let shape = new paper.Path.RegularPolygon({
// position: new paper.Point([
// ball.position.x,
// ball.position.y,
// ]),
// sides: Math.floor(Math.random() * 8),
// radius: 100,
// fillColor: 'tomato',
// });
// shape.rotate(ball.angle);
});
const shape = new paper.Path.RegularPolygon({
position: new paper.Point([
ball.position.x,
ball.position.y,
]),
sides: 5,
radius: 100,
fillColor: 'tomato',
});
shape.rotate(ball.angle);
raf.current = requestAnimationFrame(callback);
};
raf.current = requestAnimationFrame(callback);
return () => {
cancelAnimationFrame(raf.current);
Render.stop(render);
World.clear(engine.current.world);
Engine.clear(engine.current);
render.canvas.remove();
render.canvas = null;
render.context = null;
render.textures = {};
};
});
}, []);
return (
<div className=''>
<div className='paper'>
<canvas
resize='true'
ref={paperRef}
style={{
width: '100%',
height: '100%',
position: 'fixed',
top: 0,
left: 0,
}}
/>
</div>
<div
ref={scene}
style={{
display: 'none',
width: '100%',
height: '100%',
position: 'fixed',
top: 0,
left: 0,
}}
/>
</div>
);
}
export default Canvas;

In LightningChartJS, is there a way to do a drag zoom where the zoom for X and Y is always equal?

My problem is when I drag rectangle zoom for example (gyazo gif), the X axis is wider than the Y. In effect, the X axis is zoomed in more details than the Y and the visual of the graph looks different from the original graph.
https://gyazo.com/749db917465a8037b7c5f21792f572ce
I am looking for a way where if i zoom rectangle drag, the function is similar to zooming via mousewheel where x and y zoom feels equal.
here you will find an example how you can perform custom zoom rect instead of default and keep the ratio of the axes.
// Extract required parts from LightningChartJS.
const {
ColorRGBA,
ColorHEX,
emptyFill,
SolidFill,
SolidLine,
translatePoint,
_point,
lightningChart
} = lcjs;
// Import data-generator from 'xydata'-library.
const {
createProgressiveTraceGenerator
} = xydata
const chart = lightningChart()
.ChartXY()
// Disable default chart interactions with left mouse button.
// .setMouseInteractionRectangleFit(false)
.setMouseInteractionRectangleZoom(false)
.setTitleFillStyle(emptyFill)
// generate data and creating the series
const series = chart.addLineSeries().setStrokeStyle(
new SolidLine({
fillStyle: new SolidFill({ color: ColorHEX('#fff') }),
thickness: 2,
}),
)
// generate data and create series
createProgressiveTraceGenerator()
.setNumberOfPoints(200)
.generate()
.toPromise()
.then((data) => {
return series.add(data)
})
// create zooming rect and dispose it
const rect = chart
.addRectangleSeries()
.add({
x: 0,
y: 0,
width: 0,
height: 0,
})
.setFillStyle(new SolidFill({ color: ColorRGBA(255, 255, 255, 30) }))
.setStrokeStyle(
new SolidLine({
thickness: 2,
fillStyle: new SolidFill({ color: ColorRGBA(255, 255, 255, 255) }),
}),
)
.dispose()
// om Mouse drag restor rectange and set position and coordinates
chart.onSeriesBackgroundMouseDrag((obj, event, button, startLocation, delta) => {
if (button !== 0) return
const startLocationOnScale = translatePoint(
chart.engine.clientLocation2Engine(startLocation.x, startLocation.y),
chart.engine.scale,
series.scale,
)
const curLocationOnScale = translatePoint(chart.engine.clientLocation2Engine(event.x, event.y), chart.engine.scale, series.scale)
const x = Math.abs(series.getBoundaries().min.x) + Math.abs(series.getBoundaries().max.x)
const y = Math.abs(series.getBoundaries().min.y) + Math.abs(series.getBoundaries().max.y)
const ratio = x / y
const width = Math.abs(curLocationOnScale.x - startLocationOnScale.x)
const height = Math.abs(curLocationOnScale.y - startLocationOnScale.y)
const heightDirection = curLocationOnScale.y - startLocationOnScale.y // check direction of rect
// check for mouse direction to prevet fit and zoom conflict
if (curLocationOnScale.x > startLocationOnScale.x) {
rect.setDimensions({
x: startLocationOnScale.x,
y: startLocationOnScale.y,
width: width > height * ratio ? width : height * ratio,
height: width > height * ratio ? (heightDirection > 0 ? width : -width) / ratio : heightDirection,
}).restore()
} else {
// prevent phantom rectangle if you change zoom to fit during the dragging
rect.setDimensions({
x: 0,
y: 0,
width: 0,
height: 0,
}).dispose()
}
})
// on mouse drag stop dispose rect and zoom relative to its dimensions
chart.onSeriesBackgroundMouseDragStop((_, event, button, startLocation) => {
if (button !== 0) return
const rectZooom = rect.getDimensionsPositionAndSize()
if (rectZooom.width !== 0) {
chart.getDefaultAxisX().setInterval(rectZooom.x, (rectZooom.x + rectZooom.width), true, true)
if(rectZooom.height > 0){
chart.getDefaultAxisY().setInterval(rectZooom.y, (rectZooom.y + Math.abs(rectZooom.height)), true, true)
}else{
chart.getDefaultAxisY().setInterval((rectZooom.y - Math.abs(rectZooom.height)),rectZooom.y, true, true)
}
}
rect.setDimensions({
x: 0,
y: 0,
width: 0,
height: 0,
}).dispose()
})
<script src="https://unpkg.com/#arction/xydata#1.4.0/dist/xydata.iife.js"></script>
<script src="https://unpkg.com/#arction/lcjs#3.0.0/dist/lcjs.iife.js"></script>

Hide / show charts in Lightning chart dashboard

I create 3 row chart like below
var charts = [];
const db = lightningChart().Dashboard({
numberOfRows: 3,
numberOfColumns: 1
})
charts[0] = db.createChartXY({
columnIndex: 0,
rowIndex: 0,
columnSpan: 1,
rowSpan: 1,
})
similiarly for charts[1] and charts[2]
Is there anyway we can hide charts[0] and show 1 and 2 ,, or show 2 and hide charts[0] and charts[1] programatically, like legends toggle ?
Currently only way to achieve this is to dispose the chart in the cell and then create a new chart on the same cell. This means that you would need to be able to create the charts from scratch every time you want to change which chart is visible.
To remove the existing chart you can call dispose() on the chart.
chart.dispose()
Then you can create the chart you want to show. You most likely want to make a function to create the chart for you.
const createChart1 = () => {
const chart = dashboard.createChartXY({
columnIndex: 0,
rowIndex: 0
})
chart.setTitle('Chart 1')
return chart
}
const {
lightningChart,
} = lcjs
const lc = lightningChart()
const dashboard = lc.Dashboard({
numberOfColumns: 1,
numberOfRows: 2
})
const createChart1 = () => {
const chart = dashboard.createChartXY({
columnIndex: 0,
rowIndex: 0
})
chart.setTitle('Chart 1')
return chart
}
const createChart2 = () => {
const chart = dashboard.createChartXY({
columnIndex: 0,
rowIndex: 0
})
chart.setTitle('Chart 2')
return chart
}
const createChart3 = () => {
const chart = dashboard.createChartXY({
columnIndex: 0,
rowIndex: 1
})
chart.setTitle('Chart 3')
return chart
}
// Initially have charts 1 and 3 on the dashboard
let c1 = createChart1()
const c3 = createChart3()
// After a timeout change the chart on the first row to chart 2
setTimeout(() => {
// Dispose to remove the chart 1
c1.dispose()
// Create the chart 2 on the place of chart 1
c1 = createChart2()
}, 1000)
<script src="https://unpkg.com/#arction/lcjs#2.2.1/dist/lcjs.iife.js"></script>

I just know how to use for to draw the tree, but now I want to use recursion to draw the tree

I just know how to use for to draw a tree (the tree data is the picture one, the result is picture two), but now I want to use recursion to draw the tree.
Please tell me how change writing style from for to recursive
first input point
//input point
const line_point =[0, 0, 0,
2, 151, 2,
2, 151, 2,
-62, 283, 63,
2, 151, 2,
62, 297, -58,
-62, 283, 63,
-104, 334, 74,
-62, 283, 63,
-58, 338, 45,
62, 297, -58,
67, 403, -55,
62, 297, -58,
105, 365, -86];
take out star point and end point
const star_line_x= new Array();
const star_line_y= new Array();
const star_line_z= new Array();
const end_line_x= new Array();
const end_line_y= new Array();
const end_line_z= new Array();
for (var q=0; q < line_point.length; q+=6){
star_line_x.push(line_point[q]);
}
for (var r=1; r < line_point.length; r+=6){
star_line_y.push(line_point[r]);
}
for (var s=2; s < line_point.length; s+=6){
star_line_z.push(line_point[s]);
}
for (var t=3; t < line_point.length; t+=6){
end_line_x.push(line_point[t]);
}
for (var u=4; u < line_point.length; u+=6){
end_line_y.push(line_point[u]);
}
for (var v=5; v < line_point.length; v+=6){
end_line_z.push(line_point[v]);
}
var cylinder_star_point = new Array();
var cylinder_end_point = new Array();
//star_point end_point
for (var w=0; w < line_point.length/6; w++){
var star_point = new THREE.Vector3 (star_line_x[w],star_line_y[w],star_line_z[w]);
var end_point = new THREE.Vector3 (end_line_x[w],end_line_y[w],end_line_z[w]);
cylinder_star_point.push( star_point);
cylinder_end_point.push( end_point);
}
calculation cylinder high
//calculation cylinder high
var line_len = new Array();
for (var dd=0; dd < line_point.length/6; dd++){
var len_x = Math.pow(end_line_x[dd]-star_line_x[dd],2);
var len_y = Math.pow(end_line_y[dd]-star_line_y[dd],2);
var len_z = Math.pow(end_line_z[dd]-star_line_z[dd],2);
var len_direction = Math.sqrt(len_x+len_y+len_z);
line_len.push(len_direction);//Cylinder high
}
calculation center point
//center_point
const cylinder_center_point= new Array();
for (var bb=0; bb< cylinder_end_point.length; bb++){
var star_set_point = cylinder_star_point[bb];
var end_set_point = cylinder_end_point[bb];
var center_point = end_set_point.clone().add(star_set_point).divideScalar(2);
cylinder_center_point.push(center_point);
}
calculation cylinder direction vector
//cylinder direction
const cylinder_direction= new Array();
for (var cc=0; cc < cylinder_end_point.length; cc++){
var star_direction = cylinder_star_point[cc];
var end_direction = cylinder_end_point[cc];
var center_direction = end_direction.clone().sub(star_direction);
cylinder_direction.push(center_direction);
}
draw cylinder
for (var dd=0; dd <cylinder_direction.length;dd++){
var material = new THREE.MeshPhongMaterial({color:'#ff0000'});
let upVector = new THREE.Vector3(0, 1, 0);
var geometry = new THREE.CylinderGeometry(5, 5, line_len[dd], 20, 1, false);
var mesh = new THREE.Mesh(geometry, material);
mesh.position.set(0, line_len[dd]/2, 0);
var group = new THREE.Group();
group.position.set(star_line_x[dd],star_line_y[dd],star_line_z[dd]);
group.add(mesh);
let targetVector =cylinder_direction[dd];
let quaternion = new THREE.Quaternion().setFromUnitVectors(upVector, targetVector.normalize());
group.setRotationFromQuaternion(quaternion)
scene.add(group)
}
picture two: use for to draw the tree
For a tree the simplest method is to start with just a tree depth and assume 2 children. The function makes one branch and if depth > 0 then it recursively calls itself to make 2 more branches.
const numBranches = 2;
const spread = 1.5;
const branchShrinkFactor = 0.8;
const branchSpreadFactor = 0.8;
function addBranch(parent, depth, offset, angle, branchLength, spread) {
const material = new THREE.MeshPhongMaterial({color:'#ff0000'});
const geometry = new THREE.CylinderBufferGeometry(5, 5, branchLength, 20, 1, false);
geometry.translate(0, branchLength / 2, 0);
const mesh = new THREE.Mesh(geometry, material);
mesh.position.y = offset;
mesh.rotation.z = angle;
parent.add(mesh);
if (depth > 1) {
for (let i = 0; i < numBranches; ++i) {
const a = i / (numBranches - 1) - 0.5;
addBranch(mesh, depth - 1, branchLength, a * spread, branchLength * branchShrinkFactor, spread * branchSpreadFactor)
}
}
}
addBranch(scene, 5, 0, 0, 100, 1.5);
body {
margin: 0;
}
#c {
width: 100vw;
height: 100vh;
display: block;
}
<canvas id="c"></canvas>
<script type="module">
import * as THREE from 'https://threejsfundamentals.org/threejs/resources/threejs/r115/build/three.module.js';
function main() {
const canvas = document.querySelector('#c');
const renderer = new THREE.WebGLRenderer({canvas});
const fov = 75;
const aspect = 2; // the canvas default
const near = 1;
const far = 1000;
const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
camera.position.set(0, 150, 300);
const scene = new THREE.Scene();
scene.background = new THREE.Color('lightskyblue');
{
const color = 0xFFFFFF;
const intensity = 1;
const light = new THREE.DirectionalLight(color, intensity);
light.position.set(-1, 2, 4);
scene.add(light);
}
const numBranches = 2;
const spread = 1.5;
const branchShrinkFactor = 0.8;
const branchSpreadFactor = 0.8;
function addBranch(parent, depth, offset, angle, branchLength, spread) {
const material = new THREE.MeshPhongMaterial({color:'#ff0000'});
const geometry = new THREE.CylinderBufferGeometry(5, 5, branchLength, 20, 1, false);
geometry.translate(0, branchLength / 2, 0);
const mesh = new THREE.Mesh(geometry, material);
mesh.position.y = offset;
mesh.rotation.z = angle;
parent.add(mesh);
if (depth > 1) {
for (let i = 0; i < numBranches; ++i) {
const a = i / (numBranches - 1) - 0.5;
addBranch(mesh, depth - 1, branchLength, a * spread, branchLength * branchShrinkFactor, spread * branchSpreadFactor)
}
}
}
addBranch(scene, 5, 0, 0, 100, 1.5);
function resizeRendererToDisplaySize(renderer) {
const canvas = renderer.domElement;
const width = canvas.clientWidth;
const height = canvas.clientHeight;
const needResize = canvas.width !== width || canvas.height !== height;
if (needResize) {
renderer.setSize(width, height, false);
}
return needResize;
}
function render(time) {
time *= 0.001;
if (resizeRendererToDisplaySize(renderer)) {
const canvas = renderer.domElement;
camera.aspect = canvas.clientWidth / canvas.clientHeight;
camera.updateProjectionMatrix();
}
renderer.render(scene, camera);
// requestAnimationFrame(render);
}
requestAnimationFrame(render);
}
main();
</script>
If you want specific data for each branch then you need to pass that in. For example
const tree = [
{ length: 100, angle: 0, branches: 2 }, // root
{ length: 40, angle: -1, branches: 3 }, // first branch
{ length: 50, angle: 0.8, branches: 0 }, // 1st child branch
{ length: 40, angle: 0.3, branches: 0 }, // 2nd child branch
{ length: 30, angle: -0.3, branches: 0 }, // 3rd child branch
{ length: 50, angle: 0.8, branches: 2 }, // second branch
{ length: 50, angle: 0.5, branches: 0 }, // 1st child branch
{ length: 40, angle: -0.6, branches: 2 }, // 2nd child branch
{ length: 40, angle: -0.3, branches: 0 }, // 1st grandchild branch
{ length: 95, angle: 0.3, branches: 0 }, // 2st grandchild branch
];
and then walk the tree description, if a branches for a particular branch is > 0 then it recursively calls itself to add those branches. Each branches consumes a row in the array of branches so we pass back ndx so we can tell how many rows were consumed.
function addBranch(parent, offset, tree, ndx = 0) {
const {length, angle, branches} = tree[ndx];
const material = new THREE.MeshPhongMaterial({color:'#ff0000'});
const geometry = new THREE.CylinderGeometry(5, 5, length, 20, 1, false);
geometry.translate(0, length / 2, 0);
const mesh = new THREE.Mesh(geometry, material);
mesh.position.y = offset;
mesh.rotation.z = angle;
parent.add(mesh);
for (let i = 0; i < branches; ++i) {
ndx = addBranch(mesh, length, tree, ++ndx);
}
return ndx;
}
addBranch(scene, 0, tree);
body {
margin: 0;
}
#c {
width: 100vw;
height: 100vh;
display: block;
}
<canvas id="c"></canvas>
<script type="module">
import * as THREE from 'https://threejsfundamentals.org/threejs/resources/threejs/r115/build/three.module.js';
function main() {
const canvas = document.querySelector('#c');
const renderer = new THREE.WebGLRenderer({canvas});
const fov = 75;
const aspect = 2; // the canvas default
const near = 1;
const far = 1000;
const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
camera.position.set(0, 150, 300);
const scene = new THREE.Scene();
scene.background = new THREE.Color('lightskyblue');
{
const color = 0xFFFFFF;
const intensity = 1;
const light = new THREE.DirectionalLight(color, intensity);
light.position.set(-1, 2, 4);
scene.add(light);
}
const tree = [
{ length: 100, angle: 0, branches: 2 }, // root
{ length: 40, angle: -1, branches: 3 }, // first branch
{ length: 50, angle: 0.8, branches: 0 }, // 1st child branch
{ length: 40, angle: 0.3, branches: 0 }, // 2nd child branch
{ length: 30, angle: -0.3, branches: 0 }, // 3rd child branch
{ length: 50, angle: 0.8, branches: 2 }, // second branch
{ length: 50, angle: 0.5, branches: 0 }, // 1st child branch
{ length: 40, angle: -0.6, branches: 2 }, // 2nd child branch
{ length: 40, angle: -0.3, branches: 0 }, // 1st grandchild branch
{ length: 95, angle: 0.3, branches: 0 }, // 2st grandchild branch
];
function addBranch(parent, offset, tree, ndx = 0) {
const {length, angle, branches} = tree[ndx];
const material = new THREE.MeshPhongMaterial({color:'#ff0000'});
const geometry = new THREE.CylinderGeometry(5, 5, length, 20, 1, false);
geometry.translate(0, length / 2, 0);
const mesh = new THREE.Mesh(geometry, material);
mesh.position.y = offset;
mesh.rotation.z = angle;
parent.add(mesh);
for (let i = 0; i < branches; ++i) {
ndx = addBranch(mesh, length, tree, ++ndx);
}
return ndx;
}
addBranch(scene, 0, tree);
function resizeRendererToDisplaySize(renderer) {
const canvas = renderer.domElement;
const width = canvas.clientWidth;
const height = canvas.clientHeight;
const needResize = canvas.width !== width || canvas.height !== height;
if (needResize) {
renderer.setSize(width, height, false);
}
return needResize;
}
function render(time) {
time *= 0.001;
if (resizeRendererToDisplaySize(renderer)) {
const canvas = renderer.domElement;
camera.aspect = canvas.clientWidth / canvas.clientHeight;
camera.updateProjectionMatrix();
}
renderer.render(scene, camera);
// requestAnimationFrame(render);
}
requestAnimationFrame(render);
}
main();
</script>
It's not clear to me what your input data is. Your tree has a depth of 3 and 2 branches per level so this data would work
const endPoints = [
[ 0, 0, 0], // A
[ 2, 151, 2], // B
[ -62, 283, 63], // C
[-104, 334, 74], // E
[ -58, 338, 45], // F
[ 62, 296, -58], // D
[ 67, 403, -55], // G
[ 105, 365, -86], // H
];
using this code
// assumes there are 2 branches per
function addBranch(parent, depth, offset, tree, parentNdx = 0, childNdx = 1) {
const start = tree[parentNdx];
const end = tree[childNdx];
const length = start.distanceTo(end);
const material = new THREE.MeshPhongMaterial({color:'#ff0000'});
const geometry = new THREE.CylinderGeometry(5, 5, length, 20, 1, false);
geometry.translate(0, length / 2, 0);
geometry.rotateX(Math.PI / 2);
const mesh = new THREE.Mesh(geometry, material);
mesh.position.z = offset;
parent.add(mesh);
mesh.lookAt(end);
let ndx = childNdx + 1;
if (depth > 1) {
const numBranches = 2;
for (let i = 0; i < numBranches; ++i) {
ndx = addBranch(mesh, depth - 1, length, tree, childNdx, ndx);
}
}
return ndx;
}
addBranch(scene, 3, 0, tree);
I pointed the cylinders in the positive Z direction which means I can use lookAt to point the cylinder from its start to its end point.
body {
margin: 0;
}
#c {
width: 100vw;
height: 100vh;
display: block;
}
<canvas id="c"></canvas>
<script type="module">
import * as THREE from 'https://threejsfundamentals.org/threejs/resources/threejs/r115/build/three.module.js';
function main() {
const canvas = document.querySelector('#c');
const renderer = new THREE.WebGLRenderer({canvas});
const fov = 75;
const aspect = 2; // the canvas default
const near = 1;
const far = 1000;
const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
camera.position.set(250, 170, 250);
camera.lookAt(0, 170, 0);
const scene = new THREE.Scene();
scene.background = new THREE.Color('lightskyblue');
{
const color = 0xFFFFFF;
const intensity = 1;
const light = new THREE.DirectionalLight(color, intensity);
light.position.set(-1, 2, 4);
scene.add(light);
}
const tree = [
[ 0, 0, 0], // A
[ 2, 151, 2], // B
[ -62, 283, 63], // C
[-104, 334, 74], // E
[ -58, 338, 45], // F
[ 62, 296, -58], // D
[ 67, 403, -55], // G
[ 105, 365, -86], // H
].map(v => new THREE.Vector3().fromArray(v));
// assumes there are 2 branches per
function addBranch(parent, depth, offset, tree, parentNdx = 0, childNdx = 1) {
const start = tree[parentNdx];
const end = tree[childNdx];
const length = start.distanceTo(end);
const material = new THREE.MeshPhongMaterial({color:'#ff0000'});
const geometry = new THREE.CylinderGeometry(5, 5, length, 20, 1, false);
geometry.translate(0, length / 2, 0);
geometry.rotateX(Math.PI / 2);
const mesh = new THREE.Mesh(geometry, material);
mesh.position.z = offset;
parent.add(mesh);
mesh.lookAt(end);
let ndx = childNdx + 1;
if (depth > 1) {
const numBranches = 2;
for (let i = 0; i < numBranches; ++i) {
ndx = addBranch(mesh, depth - 1, length, tree, childNdx, ndx);
}
}
return ndx;
}
addBranch(scene, 3, 0, tree);
function resizeRendererToDisplaySize(renderer) {
const canvas = renderer.domElement;
const width = canvas.clientWidth;
const height = canvas.clientHeight;
const needResize = canvas.width !== width || canvas.height !== height;
if (needResize) {
renderer.setSize(width, height, false);
}
return needResize;
}
function render(time) {
time *= 0.001;
if (resizeRendererToDisplaySize(renderer)) {
const canvas = renderer.domElement;
camera.aspect = canvas.clientWidth / canvas.clientHeight;
camera.updateProjectionMatrix();
}
renderer.render(scene, camera);
// requestAnimationFrame(render);
}
requestAnimationFrame(render);
}
main();
</script>
note: this only one of infinite ways to create the tree recursively. Rather than an array in depth first order you could also create a tree structure to pass into the algorithm
const E = {
pos: [-104, 334, 74],
};
const F = {
pos: [ -58, 338, 45],
};
const C = {
pos: [ -62, 283, 63],
children: [E, F],
};
const G = {
pos: [ 67, 403, -55],
};
const H = {
pos: [ 105, 365, -86],
};
const D = {
pos: [ 62, 296, -58],
children: [G, H],
};
const B = {
pos: [ 2, 151, 2],
children: [C, D],
};
const A = {
pos: [0, 0, 0],
children: [B],
};
function addBranch(parent, branch, offset = 0) {
const {pos, children} = branch;
const start = new THREE.Vector3().fromArray(pos);
for (const child of children) {
const end = new THREE.Vector3().fromArray(child.pos);
const length = start.distanceTo(end);
const geometry = new THREE.CylinderGeometry(5, 5, length, 20, 1, false);
geometry.translate(0, length / 2, 0);
geometry.rotateX(Math.PI / 2);
const material = new THREE.MeshPhongMaterial({color: 'red'});
const mesh = new THREE.Mesh(geometry, material);
mesh.position.z = offset;
parent.add(mesh);
mesh.lookAt(end);
if (child.children) {
addBranch(mesh, child, length);
}
}
}
addBranch(scene, A);
body {
margin: 0;
}
#c {
width: 100vw;
height: 100vh;
display: block;
}
<canvas id="c"></canvas>
<script type="module">
import * as THREE from 'https://threejsfundamentals.org/threejs/resources/threejs/r115/build/three.module.js';
function main() {
const canvas = document.querySelector('#c');
const renderer = new THREE.WebGLRenderer({canvas});
const fov = 75;
const aspect = 2; // the canvas default
const near = 1;
const far = 1000;
const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
camera.position.set(250, 170, 250);
camera.lookAt(0, 170, 0);
const scene = new THREE.Scene();
scene.background = new THREE.Color('lightskyblue');
{
const color = 0xFFFFFF;
const intensity = 1;
const light = new THREE.DirectionalLight(color, intensity);
light.position.set(-1, 2, 4);
scene.add(light);
}
const E = {
pos: [-104, 334, 74],
};
const F = {
pos: [ -58, 338, 45],
};
const C = {
pos: [ -62, 283, 63],
children: [E, F],
};
const G = {
pos: [ 67, 403, -55],
};
const H = {
pos: [ 105, 365, -86],
};
const D = {
pos: [ 62, 296, -58],
children: [G, H],
};
const B = {
pos: [ 2, 151, 2],
children: [C, D],
};
const A = {
pos: [0, 0, 0],
children: [B],
};
function addBranch(parent, branch, offset = 0) {
const {pos, children} = branch;
const start = new THREE.Vector3().fromArray(pos);
for (const child of children) {
const end = new THREE.Vector3().fromArray(child.pos);
const length = start.distanceTo(end);
const geometry = new THREE.CylinderGeometry(5, 5, length, 20, 1, false);
geometry.translate(0, length / 2, 0);
geometry.rotateX(Math.PI / 2);
const material = new THREE.MeshPhongMaterial({color: 'red'});
const mesh = new THREE.Mesh(geometry, material);
mesh.position.z = offset;
parent.add(mesh);
mesh.lookAt(end);
if (child.children) {
addBranch(mesh, child, length);
}
}
}
addBranch(scene, A);
function resizeRendererToDisplaySize(renderer) {
const canvas = renderer.domElement;
const width = canvas.clientWidth;
const height = canvas.clientHeight;
const needResize = canvas.width !== width || canvas.height !== height;
if (needResize) {
renderer.setSize(width, height, false);
}
return needResize;
}
function render(time) {
time *= 0.001;
if (resizeRendererToDisplaySize(renderer)) {
const canvas = renderer.domElement;
camera.aspect = canvas.clientWidth / canvas.clientHeight;
camera.updateProjectionMatrix();
}
renderer.render(scene, camera);
// requestAnimationFrame(render);
}
requestAnimationFrame(render);
}
main();
</script>

d3.js: why don't the columns in my column chart contain the full data?

I am using a slightly modified reusable column chart script from https://gist.github.com/llad/3766585
Works great. However, I was just trying to add some tooltips on hover, that would display additional data from the JSON file for each column, but the additional data is not there. I look in the inspector and just see the two values used to calculate x and y. Is there something obvious in the way the script is written that is not binding the full data set?
The script:
function columnChart() {
var margin = {top: 30, right: 10, bottom: 50, left: 50},
width = 420,
height = 420,
xRoundBands = 0.2,
xValue = function(d) { return d[0]; },
yValue = function(d) { return d[1]; },
xScale = d3.scale.ordinal(),
yScale = d3.scale.linear(),
xFormat = '',
yFormat = '',
yAxis = d3.svg.axis().scale(yScale).orient("left"),
xAxis = d3.svg.axis().scale(xScale);
function chart(selection) {
selection.each(function(data) {
// Convert data to standard representation greedily;
// this is needed for nondeterministic accessors.
data = data.map(function(d, i) {
return [xValue.call(data, d, i), yValue.call(data, d, i)];
});
// Update the x-scale.
xScale
.domain(data.map(function(d) { return d[0];} ))
.rangeRoundBands([0, width - margin.left - margin.right], xRoundBands);
// Update the y-scale.
yScale
.domain(d3.extent(data.map(function(d) { return d[1];} )))
.range([height - margin.top - margin.bottom, 0])
.nice();
// Select the svg element, if it exists.
var svg = d3.select(this).selectAll("svg").data([data]);
// Otherwise, create the skeletal chart.
var gEnter = svg.enter().append("svg").append("g");
gEnter.append("g").attr("class", "bars");
gEnter.append("g").attr("class", "y axis");
gEnter.append("g").attr("class", "x axis");
gEnter.append("g").attr("class", "x axis zero");
// Update the outer dimensions.
svg .attr("width", width)
.attr("height", height);
// Update the inner dimensions.
var g = svg.select("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// Update the bars.
var bar = svg.select(".bars").selectAll(".bar").data(data);
bar.enter().append("rect");
bar.exit().remove();
bar.attr("class", function(d, i) { return d[1] < 0 ? "bar negative" : "bar positive"; })
.attr("x", function(d) { return X(d); })
.attr("y", function(d, i) { return d[1] < 0 ? Y0() : Y(d); })
.attr("width", xScale.rangeBand())
.attr("height", function(d, i) { return Math.abs( Y(d) - Y0() ); })
.on("click", function(d, i)
{
d3.selectAll('.bar').classed('fade', true);
d3.select(this).classed("sel", true).classed("fade", false);
})
.on("mouseover", function(d, i)
{
d3.select(this).classed("hover", true);
})
.on("mouseout", function(d, i)
{
d3.select(this).classed("hover", false);
});
// x axis at the bottom of the chart
g.select(".x.axis")
.attr("transform", "translate(0," + (height - margin.top - margin.bottom) + ")")
.call(xAxis.orient("bottom").tickFormat(xFormat));
// zero line
g.select(".x.axis.zero")
.attr("transform", "translate(0," + Y0() + ")")
.call(xAxis.tickFormat("").tickSize(0));
// Update the y-axis.
g.select(".y.axis")
.call(yAxis);
// Horizontal grid
g.insert("g", ".bars")
.attr("class", "grid horizontal")
.call(d3.svg.axis().scale(yScale)
.orient("left")
.tickSize(-(width-margin.left-margin.right), 0, 0)
.tickFormat("")
);
});
}
// The x-accessor for the path generator; xScale ∘ xValue.
function X(d) {
return xScale(d[0]);
}
function Y0() {
return yScale(0);
}
// The x-accessor for the path generator; yScale ∘ yValue.
function Y(d) {
return yScale(d[1]);
}
chart.margin = function(_) {
if (!arguments.length) return margin;
margin = _;
return chart;
};
chart.width = function(_) {
if (!arguments.length) return width;
width = _;
return chart;
};
chart.height = function(_) {
if (!arguments.length) return height;
height = _;
return chart;
};
chart.x = function(_) {
if (!arguments.length) return xValue;
xValue = _;
return chart;
};
chart.y = function(_) {
if (!arguments.length) return yValue;
yValue = _;
return chart;
};
chart.yTickFormat = function(_) {
if (!arguments.length) return yFormat;
yFormat = _;
return chart;
};
chart.xTickFormat = function(_) {
if (!arguments.length) return xFormat;
xFormat = _;
return chart;
};
return chart;
}
The initialization:
function renderGraph(view){
var chartWidth = mainWidth();
var chartHeight = 400;
var parseDate = d3.time.format("%Y-%m-%d").parse;
var xFormat = d3.time.format("%b %e");
var data = [];
var req = $.ajax({
url: '/data/column-data.json',
type: 'GET',
dataType: 'json',
success: function(response) {
data = response;
}
});
$.when(req).done(function() {
d3.select("#columnChart")
.datum(data.widgets)
.call(columnChart()
.width(chartWidth)
.height(chartHeight)
.x(function(d, i) { return parseDate(d[0]); })
.xTickFormat(xFormat)
.y(function(d, i) {
var yData;
if (view === 'thisView'){
yData = d[1];
}else if (view === 'thatView'){
yData = d[2];
}
return yData;
}));
});
}
and the data looks like this:
{ "widgets" : [
["2013-09-15", 1, 66622, 1, 3],
["2013-09-16", 0, 0, 0, 0],
["2013-09-17", 2, 76316, 2, 2],
["2013-09-18", 4, 291244, 8, 12],
["2013-09-19", 1, 74674, 2, 2],
["2013-09-20", 5, 287965, 7, 5],
["2013-09-21", 0, 0, 0, 0],
["2013-09-22", 0, 0, 0, 0],
["2013-09-23", 7, 459249, 15, 22],
["2013-09-24", 2, 317320, 1, 6],
["2013-09-25", 3, 100269, 3, 10],
["2013-09-26", 4, 181080, 8, 4],
["2013-09-27", 1, 38056, 1, 1],
["2013-09-28", 0, 0, 0, 0],
["2013-09-29", 0, 0, 0, 0],
["2013-09-30", 3, 449334, 2, 13],
["2013-10-01", 9, 403929, 5, 15],
["2013-10-02", 4, 222512, 7, 12],
["2013-10-03", 1, 196012, 3, 9],
["2013-10-04", 2, 391716, 2, 8],
["2013-10-05", 0, 0, 0, 0],
["2013-10-06", 0, 0, 0, 0],
["2013-10-07", 4, 260312, 8, 14],
["2013-10-08", 1, 34350, 1, 1],
["2013-10-09", 3, 179067, 9, 18],
["2013-10-10", 2, 124250, 8, 19],
["2013-10-11", 2, 381186, 4, 9],
["2013-10-12", 0, 0, 0, 0],
["2013-10-13", 0, 0, 0, 0],
["2013-10-14", 5, 393400, 11, 17]
]
}
The tooltip should display the full data for any one column. The web inspector shows an array of 2 for each column (I'm expecting an array of 5)
How do I modify the script to bind the full data for each column?
Thanks!
UPDATE:
I still haven't solved this, though #adam-pearce got very close. I've put together a couple jsbin's to help.
A bin for the original script is here: http://jsbin.com/EjugosA/2/edit
and the script with Adam's answer is here: http://jsbin.com/IPoDutA/1/edit
this just has the following commented out:
//data = data.map(function(d, i) {
// return [xValue.call(data, d, i), yValue.call(data, d, i)];
//});
You can see in the second that both x and y axis fail to render, though the full data set I wanted is bound to each bar. The web inspector shows the following error:
'undefined' is not a function (evaluating 'd.getMonth()')" which points to line 8410 in d3.v3.js, in d3_time_formats.
How to I modify this script to get the full data without breaking the axis?
data = data.map(function(d, i) {
return [xValue.call(data, d, i), yValue.call(data, d, i)];
});
Removes everything but the first two columns from data. Looking over the code, I think it would still work if you commented out those three lines.
In responce to your comment:
// x axis at the bottom of the chart
g.select(".x.axis")
.attr("transform", "translate(0," + (height - margin.top - margin.bottom) + ")")
.call(xAxis.orient("bottom"));//.tickFormat(xFormat));
You're trying to print strings as dates which doesn't work without parsing the strings first.

Resources