I have to draw multi series by using 3d plot so I've test highcharts scatter 3d like this demo:
// Set up the chart
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'scatter',
options3d: {
enabled: true,
alpha: 10,
beta: 30,
depth: 250,
viewDistance: 15,
fitToPlot: false,
}
},
yAxis: {
min: 0,
max: 10,
title: null
},
xAxis: {
min: 0,
max: 10,
gridLineWidth: 1
},
zAxis: {
min: 0,
max: 10,
showFirstLabel: false
},
plotOptions: {
series: {
marker: {
enabled: true
},
lineWidth: 2,
}
},
series: [{
lineColor: 'red',
data: (function() {
var data = [];
for (var i = 0; i < 1000; i++) {
data.push([i / 100, 3 + Math.random(), 0]);
}
return data;
})()
},{
lineColor: 'blue',
data: (function() {
var data = [];
for (var i = 0; i < 1000; i++) {
data.push([i / 100, 3 + Math.random(), 3]);
}
return data;
})()
},{
lineColor: 'green',
data: (function() {
var data = [];
for (var i = 0; i < 1000; i++) {
data.push([i / 100, 3 + Math.random(), 6]);
}
return data;
})()
},{
lineColor: 'yellow',
data: (function() {
var data = [];
for (var i = 0; i < 1000; i++) {
data.push([i / 100, 3 + Math.random(), 9]);
}
return data;
})()
}
/* ,{
lineColor: 'black',
type: 'polygon',
data: (function() {
var data = [];
for (var i = 0; i < 100; i++) {
data.push([3, 3 + 5 * Math.random(), i / 10]);
}
data.push([3, 0, i / 10]);
data.push([3, 0, 0])
return data;
})()
} */
]
});
// Add mouse events for rotation
$(chart.container).on('mousedown.hc touchstart.hc', function(eStart) {
eStart = chart.pointer.normalize(eStart);
var posX = eStart.pageX,
posY = eStart.pageY,
alpha = chart.options.chart.options3d.alpha,
beta = chart.options.chart.options3d.beta,
newAlpha,
newBeta,
sensitivity = 5; // lower is more sensitive
$(document).on({
'mousemove.hc touchdrag.hc': function(e) {
// Run beta
newBeta = beta + (posX - e.pageX) / sensitivity;
chart.options.chart.options3d.beta = newBeta;
// Run alpha
newAlpha = alpha + (e.pageY - posY) / sensitivity;
chart.options.chart.options3d.alpha = newAlpha;
chart.redraw(false);
},
'mouseup touchend': function() {
$(document).off('.hc');
}
});
});
plz click the link to view:http://jsfiddle.net/willxiang/x7wqfLh3/
if i disabled marker (plotOptions->series->marker:false),it look like perfect.
But i need show tooltips when mouse move on series to display the point info,so i enabled marker,
and the chart performance is bad...(in this demo 4 series 4000 point)
Please anybody help me to improve performance ~
Thanks !
After digging into it I think that the only for could be done for it is disabling markers while 3d rotating and enabling when it is finished. The performance is not perfect still but that is all that could be done to increase it for those conditions.
Demo: http://jsfiddle.net/BlackLabel/m4rpfdn0/
// Add mouse events for rotation
$(chart.container).on('mousedown.hc touchstart.hc', function(eStart) {
eStart = chart.pointer.normalize(eStart);
var posX = eStart.pageX,
posY = eStart.pageY,
alpha = chart.options.chart.options3d.alpha,
beta = chart.options.chart.options3d.beta,
newAlpha,
newBeta,
sensitivity = 5; // lower is more sensitive
$(document).on({
'mousemove.hc touchdrag.hc': function(e) {
chart.tooltip.destroy();
chart.series.forEach(function(s) {
s.update({
marker: {
enabled: false
}
}, false)
});
// Run beta
newBeta = beta + (posX - e.pageX) / sensitivity;
if (Math.abs(chart.options.chart.options3d.beta - newBeta) > 5) {
chart.options.chart.options3d.beta = newBeta;
}
// Run alpha
newAlpha = alpha + (e.pageY - posY) / sensitivity;
if (Math.abs(chart.options.chart.options3d.alpha - newAlpha) > 5) {
chart.options.chart.options3d.alpha = newAlpha;
}
chart.redraw(false);
},
'mouseup touchend': function() {
$(document).off('.hc');
chart.tooltip.destroy();
chart.series.forEach(function(s) {
s.update({
marker: {
enabled: true
}
}, false)
});
chart.redraw();
}
});
});
Related
How to show the min and max or x and x2 values in the chart and Need the partial fill to in value than %.
min = 0;
max = 150;
y=95; //points scored.
{
showInLegend: false,
pointWidth: 25,
data: [{
x: 0,
x2: 150,
y: 0,
partialFill: 0.75
}],
dataLabels: {
enabled: true
}
}
0 -------------------95points---------------150
Fiddle Example: https://jsfiddle.net/bv4uyazq/
If I understood you correctly you can achieve it following these approaches:
1) render custom labels using SVGRenderer:
Code:
chart: {
type: 'xrange',
events: {
render: function() {
var chart = this,
offsetTop = -8,
offsetLetf = 5,
x1,
x2,
y,
label1,
label2,
label2BBox;
if (chart.customLabels && chart.customLabels.length) {
chart.customLabels.forEach(function(label) {
label.destroy();
});
}
chart.customLabels = [];
chart.series[0].points.forEach(function(point) {
x1 = point.plotX + chart.plotLeft + offsetLetf;
x2 = x1 + point.shapeArgs.width - 2 * offsetLetf;
y = point.plotY + chart.plotTop + point.shapeArgs.height / 2 + offsetTop;
label1 = chart.renderer.text(chart.xAxis[0].dataMin, x1, y).css({
fill: '#fff'
}).add().toFront();
label2 = chart.renderer.text(chart.xAxis[0].dataMax, x2, y).css({
fill: '#fff'
}).add().toFront();
label2BBox = label2.getBBox();
label2.translate(-label2BBox.width, 0);
chart.customLabels.push(label1);
chart.customLabels.push(label2);
});
}
}
}
Demo:
https://jsfiddle.net/BlackLabel/twuv96ex/1/
2) set xAxis labels positions as dataMin and dataMax and translate it using offset property:
Code:
xAxis: {
type: 'linear',
visible: true,
offset: -110,
tickPositioner: function() {
return [this.dataMin, this.dataMax];
}
}
Demo:
https://jsfiddle.net/BlackLabel/m7s4pfo5/
API reference:
https://api.highcharts.com/class-reference/Highcharts.SVGRenderer#text
https://api.highcharts.com/class-reference/Highcharts.DataLabelsOptionsObject#formatter
https://api.highcharts.com/highcharts/xAxis.offset
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have an image of a data visualization that I want to make into 3D. I was wondering how I would be able to convert this image into 3D using three.js and other possible tools. I have no idea what to do.
I heard that there is something called WebGL Javascript API so maybe I can use that but I don't know how to begin and whether or not it can be used in this situation. I also read somewhere that you cannot make a 3D image from a 2D one without some information about the 3rd dimension. This missing information can come from a second photo, an AI software, or a 3D digital model.
I also read that I can make a 3D model of the image in Blender and then import it into three.js.
Does anyone know how I can do this?
I want to try to do the coding in JS fiddle if it's possible unless other software/tools are needed outside of JS fiddle. I see that you can import the three.js library there.
The current visualization I have made is
My code for this visualization if you need it is:
$(function() {
var dataEx = [
['1 Visit', 352000],
['2 Visits', 88000],
['3+ Visits', 42000]
],
len = dataEx.length,
sum = 0,
minHeight = 0.05,
data = [];
//specify your percent of prior visit value manually here:
var perc = [100, 25, 48];
for (var i = 0; i < len; i++) {
sum += dataEx[i][1];
}
for (var i = 0; i < len; i++) {
var t = dataEx[i],
r = t[1] / sum;
data[i] = {
name: t[0],
y: (r > minHeight ? t[1] : sum * minHeight),
percent: perc[i], // <----- this here is manual input
//percent: Math.round(r * 100), <--- this here is mathematical
label: t[1]
}
}
console.log(dataEx, data)
$('#container').highcharts({
chart: {
type: 'funnel',
marginRight: 100,
events: {
load: function() {
var chart = this;
Highcharts.each(chart.series[0].data, function(p, i) {
var bBox = p.dataLabel.getBBox()
p.dataLabel.attr({
x: (chart.plotWidth - chart.plotLeft) / 2,
'text-anchor': 'middle',
y: p.labelPos.y - (bBox.height / 2)
})
})
},
redraw: function() {
var chart = this;
Highcharts.each(chart.series[0].data, function(p, i) {
p.dataLabel.attr({
x: (chart.plotWidth - chart.plotLeft) / 2,
'text-anchor': 'middle',
y: p.labelPos.y - (bBox.height / 2)
})
})
}
},
},
//Manually changing the default colors of each category of series
colors: ['#FF5733', '#FFA533', '#1FC009'],
title: {
text: 'New Guest Return Funnel',
x: -45
},
credits: {
enabled: false
},
tooltip: {
//enabled: false
formatter: function() {
return '<b>' + this.key +
'</b><br/>Percent of Prior Visit: '+ this.point.percent + '%<br/>Guests: ' + Highcharts.numberFormat(this.point.label, 0);
}
},
plotOptions: {
series: {
allowPointSelect: true,
borderWidth: 12,
animation: {
duration: 400
},
dataLabels: {
enabled: true,
connectorWidth: 0,
distance: 0,
formatter: function() {
var point = this.point;
console.log(point);
return '<b>' + point.name + '</b> (' + Highcharts.numberFormat(point.label, 0) + ')<br/>' + point.percent + '%';
},
minSize: '10%',
color: 'black',
softConnector: true
},
neckWidth: '30%',
neckHeight: '0%',
width: '50%',
height: '110%'
//old options are as follows:
//neckWidth: '50%',
//neckHeight: '50%',
//-- Other available options
//height: '200'
// width: pixels or percent
}
},
legend: {
enabled: false
},
series: [{
name: 'Unique users',
data: data
}]
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/funnel.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<div id="container" style="width: 500px; height: 400px; margin: 0 auto"></div>
I made you a quick and dirty example. Hopefully it gives you some ideas.
var dataEx = [
['1 Visit', 352000],
['2 Visits', 88000],
['3+ Visits', 42000]
],
len = dataEx.length,
sum = 0,
minHeight = 0.05,
data = [];
//specify your percent of prior visit value manually here:
var perc = [100, 25, 48];
for (var i = 0; i < len; i++) {
sum += dataEx[i][1];
}
for (var i = 0; i < len; i++) {
var t = dataEx[i],
r = t[1] / sum;
data[i] = {
name: t[0],
y: (r > minHeight ? t[1] : sum * minHeight),
percent: perc[i], // <----- this here is manual input
//percent: Math.round(r * 100), <--- this here is mathematical
label: t[1]
}
}
console.log(dataEx, data)
var renderer = new THREE.WebGLRenderer();
var w = 300;
var h = 200;
renderer.setSize(w, h);
document.body.appendChild(renderer.domElement);
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(
45, // Field of view
w / h, // Aspect ratio
0.1, // Near
10000 // Far
);
controls = new THREE.OrbitControls(camera, renderer.domElement);
camera.position.set(0, 20, 15);
camera.lookAt(new THREE.Vector3(0, 60, 0));
controls.target.set(0, 10, 0);
var light = new THREE.PointLight(0xFFFFFF);
light.position.set(20, 20, 20);
scene.add(light);
var light1 = new THREE.AmbientLight(0x808080);
light1.position.set(20, 20, 20);
scene.add(light1);
var light2 = new THREE.PointLight(0xFFFFFF);
light2.position.set(-20, 20, -20);
scene.add(light2);
var light3 = new THREE.PointLight(0xFFFFFF);
light3.position.set(-20, -20, -20);
scene.add(light3);
function makeCanvasTexture(color, text) {
var canvas = document.createElement('canvas');
canvas.width = canvas.height = 256;
var ctx = canvas.getContext('2d');
ctx.textAlign = "center";
ctx.fillStyle = color;
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'black';
ctx.font = "30px Arial";
ctx.fillText(text, (canvas.width / 2) | 0, (canvas.height / 2) | 0);
var tex = new THREE.Texture(canvas)
tex.minFilter = THREE.LinearMipMapLinearFilter;
tex.magFilter = THREE.LinearFilter;
tex.wrapS = tex.wrapT = THREE.RepeatWrapping;
tex.needsUpdate = true;
return tex;
}
function makePlane(color, text, percent, position) {
var geom = new THREE.PlaneGeometry(1, 1);
var material = new THREE.MeshLambertMaterial({
color: 'white',
side: THREE.DoubleSide,
map: makeCanvasTexture(color, text)
});
var npct = percent / 100;
material.map.repeat.set(1, npct);
material.map.offset.set(0, 0.5 * (1 - npct));
var mesh = new THREE.Mesh(geom, material);
mesh.position.y = position;
mesh.scale.y *= percent / 100;
return mesh;
}
renderer.setClearColor(0xdddddd, 1);
var root = new THREE.Object3D();
scene.add(root);
root.scale.multiplyScalar(10);
var yOffset = 0;
var colors = ['red', 'green', 'yellow']
for (var i = 0; i < data.length; i++) {
yOffset += data[i].percent / 200
var plane = makePlane(colors[i], data[i].name, data[i].percent, yOffset);
root.add(plane);
yOffset += data[i].percent / 200
yOffset += 0.05
}
(function animate() {
requestAnimationFrame(animate);
controls.update();
renderer.render(scene, camera);
var pnow = performance.now()*0.001;
controls.target.y = (Math.sin(pnow)*10)+10
})();
<script src="https://threejs.org/build/three.min.js"></script>
<script src="https://cdn.rawgit.com/mrdoob/three.js/master/examples/js/controls/OrbitControls.js"></script>
I'm trying to reproduce something like this: http://carbure.co/.
After inspection the website uses matter.js, a physics engine. Below is a (failed) code attempt, and I'm having trouble getting it to work given the terrible docs.
Does anyone have any idea how else I can achieve this?
Many thanks
$(window).load(function() {
var w = $(window).innerWidth();
var h = $(window).innerHeight();
// Matter.js module aliases
var Engine = Matter.Engine;
var World = Matter.World;
var Bodies = Matter.Bodies;
var Body = Matter.Body;
var Constraint = Matter.Constraint;
var Composite = Matter.Composite;
var Composites = Matter.Composites;
var MouseConstraint = Matter.MouseConstraint;
// create a Matter.js engine
var engine = Engine.create({
render: {
element: document.body,
options: {
width: w,
height: h,
wireframes: false,
background: '#fff'
}
}
});
// add a mouse controlled constraint
var mouseConstraint = MouseConstraint.create(engine);
World.add(engine.world, mouseConstraint);
var addToWorld = [];
// create random poly's and a ground
var ranPolygons = Math.random() * 10 + 5 >> 0;
var prevPoly;
for (var i = 0; i < ranPolygons; i++) {
var polyRadius = Math.random() * 40 + 40 >> 0;
var polySides = 1;
var x = Math.random() * (w - polyRadius * 2) + polyRadius >> 0;
var y = Math.random() * (h / 2 - polyRadius * 2) + polyRadius >> 0;
var isStatic = Math.random() * 1 < 0.2;
var poly = Bodies.polygon(x, y, polySides, polyRadius, {
render: {
fillStyle: isStatic ? '#0134CB' : makePattern(),
strokeStyle: isStatic ? 'transparent' : '#0134CB',
lineWidth: Math.random() * 5 + 2 >> 0
},
density: Math.random() * 0.1,
isStatic: isStatic,
restitution: Math.random() * 1
});
addToWorld.push(poly);
// add borders
var border = 5;
var halfBorder = border / 2;
var borders = [
Bodies.rectangle(w / 2, halfBorder, w + border, border, {
isStatic: true,
render: {
fillStyle: 'transparent',
strokeStyle: 'transparent'
}
}),
Bodies.rectangle(w / 2, h - halfBorder, w + border, border, {
isStatic: true,
render: {
fillStyle: 'transparent',
strokeStyle: 'transparent'
}
}),
Bodies.rectangle(halfBorder, h / 2, border, h + border, {
isStatic: true,
render: {
fillStyle: 'transparent',
strokeStyle: 'transparent'
}
}),
Bodies.rectangle(w - halfBorder, h / 2, border, h + border, {
isStatic: true,
render: {
fillStyle: 'transparent',
strokeStyle: 'transparent'
}
}),
];
addToWorld = addToWorld.concat(borders);
// add all of the bodies to the world
World.add(engine.world, addToWorld);
// run the engine
runner = Engine.run(engine)
// setTimeout(ranGrav, 2000);
engine.world.gravity.y = 0;
engine.world.gravity.x = 0;
$(engine.render.canvas).css({
width: '100%',
height: '100vh'
})
});
I got your code running. It had a number of issues. First and foremost, the missing bracket belonged to the loop:
for (var i = 0; i < ranPolygons; i++) {
Besides that I also had to run the renderer:
Render.run(render);
And I got rid of this bit, because it was unnecessary and was throwing a warning:
$(engine.render.canvas).css({
width: '100%',
height: '100vh'
});
https://jsfiddle.net/jx3vn7da/
I am attempting to implement this mousefollow into my website:
http://codepen.io/hakimel/pen/KanIi
But I would like my own custom colors instead of what is default displayed. I changed the fillcolor value and was able to change to one specific color but I would like 4 different colors. So I have tried adding specific colors to this function next to fillColor: but no such luck. I also created a fillcolor2: property like:
for (var i = 0; i < QUANTITY; i++) {
var particle = {
size: 1,
position: { x: mouseX, y: mouseY },
offset: { x: 0, y: 0 },
shift: { x: mouseX, y: mouseY },
speed: 0.01+Math.random()*0.04,
targetSize: 1,
fillColor: '#bf3e27',
fillColor2: '#1c305c',
orbit: RADIUS*.1 + (RADIUS * .5 * Math.random())
};
and added:
context.fillStyle = particle.fillColor2;
context.strokeStyle = particle.fillColor2;
But that did not work either. I have also tried to copy and paste the same js code just to see if it would work, and just changed the fillcolor, but it would only display the last one pasted.
Can anyone show me how to get 4 separate colors the easiest way, I feel like I am vastly over-complicating this but obviously a beginner and getting rather frustrated with this?
Lastly, I would like the 4 different colors to span different radii and I messed around with the different RADIUS variables but it is pretty much impossible to figure out how to accomplish what I would like while only having one color. So there will be 4 of each color, I changed the QUANTITY to:
var QUANTITY = 16;
I need the first 4 colors radius of 10 so for the first one I set:
var RADIUS = 10;
Ideally I need the first 4 to be color (#AAAAAA) radius of 10 like it is, but need the second 4 to be color (#BBBBBBB) between radius 10 and 30, the third color (#CCCCCC) to be between radius of 30-50, and the last fourth color (#DDDDDD) to be between 50 and 70.
Any suggestions?
You could replace the definition of QUANTITY, COLOR and RADIUS with an array of these, and at the same time define ranges for RADIUS:
var GROUPS = [
{
QUANTITY: 4,
RADIUS: [ 5, 10],
COLOR: 0x888888
},
{
QUANTITY: 4,
RADIUS: [10, 30],
COLOR: 0xAA80AA
},
{
QUANTITY: 4,
RADIUS: [30, 50],
COLOR: 0xA0A0CC
},
{
QUANTITY: 4,
RADIUS: [50, 70],
COLOR: 0xFFE0E0
}
];
Then inside the createParticles function you would iterate over those GROUPS:
for (var g = 0; g < GROUPS.length; g++) {
var attribs = GROUPS[g];
for (var i = 0; i < attribs.QUANTITY; i++) {
var particle = {
size: 1,
position: { x: mouseX, y: mouseY },
offset: { x: 0, y: 0 },
shift: { x: mouseX, y: mouseY },
speed: 0.01+Math.random()*0.04,
targetSize: 1,
fillColor: '#' + attribs.COLOR.toString(16),
orbit: attribs.RADIUS[0] +
(attribs.RADIUS[1]-attribs.RADIUS[0]) * Math.random()
};
particles.push( particle );
}
}
Here is a snippet:
// One of my first <canvas> experiments, woop! :D
var SCREEN_WIDTH = window.innerWidth;
var SCREEN_HEIGHT = window.innerHeight;
var GROUPS = [
{
QUANTITY: 4,
RADIUS: [ 5, 10],
COLOR: 0x888888
},
{
QUANTITY: 4,
RADIUS: [10, 30],
COLOR: 0xAA80AA
},
{
QUANTITY: 4,
RADIUS: [30, 50],
COLOR: 0xA0A0CC
},
{
QUANTITY: 4,
RADIUS: [50, 70],
COLOR: 0xFFE0E0
}
];
var RADIUS_SCALE = 1;
var RADIUS_SCALE_MIN = 1;
var RADIUS_SCALE_MAX = 1.5;
var canvas;
var context;
var particles;
var mouseX = SCREEN_WIDTH * 0.5;
var mouseY = SCREEN_HEIGHT * 0.5;
var mouseIsDown = false;
function init() {
canvas = document.getElementById( 'world' );
if (canvas && canvas.getContext) {
context = canvas.getContext('2d');
// Register event listeners
window.addEventListener('mousemove', documentMouseMoveHandler, false);
window.addEventListener('mousedown', documentMouseDownHandler, false);
window.addEventListener('mouseup', documentMouseUpHandler, false);
document.addEventListener('touchstart', documentTouchStartHandler, false);
document.addEventListener('touchmove', documentTouchMoveHandler, false);
window.addEventListener('resize', windowResizeHandler, false);
createParticles();
windowResizeHandler();
setInterval( loop, 1000 / 60 );
}
}
function createParticles() {
particles = [];
for (var g = 0; g < GROUPS.length; g++) {
var attribs = GROUPS[g];
for (var i = 0; i < attribs.QUANTITY; i++) {
var particle = {
size: 1,
position: { x: mouseX, y: mouseY },
offset: { x: 0, y: 0 },
shift: { x: mouseX, y: mouseY },
speed: 0.01+Math.random()*0.04,
targetSize: 1,
fillColor: '#' + attribs.COLOR.toString(16),
orbit: attribs.RADIUS[0] +
(attribs.RADIUS[1]-attribs.RADIUS[0]) * Math.random()
};
particles.push( particle );
}
}
}
function documentMouseMoveHandler(event) {
mouseX = event.clientX - (window.innerWidth - SCREEN_WIDTH) * .5;
mouseY = event.clientY - (window.innerHeight - SCREEN_HEIGHT) * .5;
}
function documentMouseDownHandler(event) {
mouseIsDown = true;
}
function documentMouseUpHandler(event) {
mouseIsDown = false;
}
function documentTouchStartHandler(event) {
if(event.touches.length == 1) {
event.preventDefault();
mouseX = event.touches[0].pageX - (window.innerWidth - SCREEN_WIDTH) * .5;;
mouseY = event.touches[0].pageY - (window.innerHeight - SCREEN_HEIGHT) * .5;
}
}
function documentTouchMoveHandler(event) {
if(event.touches.length == 1) {
event.preventDefault();
mouseX = event.touches[0].pageX - (window.innerWidth - SCREEN_WIDTH) * .5;;
mouseY = event.touches[0].pageY - (window.innerHeight - SCREEN_HEIGHT) * .5;
}
}
function windowResizeHandler() {
SCREEN_WIDTH = window.innerWidth;
SCREEN_HEIGHT = window.innerHeight;
canvas.width = SCREEN_WIDTH;
canvas.height = SCREEN_HEIGHT;
}
function loop() {
if( mouseIsDown ) {
RADIUS_SCALE += ( RADIUS_SCALE_MAX - RADIUS_SCALE ) * (0.02);
}
else {
RADIUS_SCALE -= ( RADIUS_SCALE - RADIUS_SCALE_MIN ) * (0.02);
}
RADIUS_SCALE = Math.min( RADIUS_SCALE, RADIUS_SCALE_MAX );
context.fillStyle = 'rgba(0,0,0,0.05)';
context.fillRect(0, 0, context.canvas.width, context.canvas.height);
for (i = 0, len = particles.length; i < len; i++) {
var particle = particles[i];
var lp = { x: particle.position.x, y: particle.position.y };
// Rotation
particle.offset.x += particle.speed;
particle.offset.y += particle.speed;
// Follow mouse with some lag
particle.shift.x += ( mouseX - particle.shift.x) * (particle.speed);
particle.shift.y += ( mouseY - particle.shift.y) * (particle.speed);
// Apply position
particle.position.x = particle.shift.x + Math.cos(i + particle.offset.x) * (particle.orbit*RADIUS_SCALE);
particle.position.y = particle.shift.y + Math.sin(i + particle.offset.y) * (particle.orbit*RADIUS_SCALE);
// Limit to screen bounds
particle.position.x = Math.max( Math.min( particle.position.x, SCREEN_WIDTH ), 0 );
particle.position.y = Math.max( Math.min( particle.position.y, SCREEN_HEIGHT ), 0 );
particle.size += ( particle.targetSize - particle.size ) * 0.05;
if( Math.round( particle.size ) == Math.round( particle.targetSize ) ) {
particle.targetSize = 1 + Math.random() * 7;
}
context.beginPath();
context.fillStyle = particle.fillColor;
context.strokeStyle = particle.fillColor;
context.lineWidth = particle.size;
context.moveTo(lp.x, lp.y);
context.lineTo(particle.position.x, particle.position.y);
context.stroke();
context.arc(particle.position.x, particle.position.y, particle.size/2, 0, Math.PI*2, true);
context.fill();
}
}
window.onload = init;
body {
background-color: #000000;
padding: 0;
margin: 0;
overflow: hidden;
}
<canvas id='world'></canvas>
Define the settings for the particles in an array
// I've changed the color for better visibility
var ParticleSettings = [
{color: "#f00", radiusMin: 10, radiusMax: 10},
{color: "#0f0", radiusMin: 10, radiusMax: 30},
{color: "#00f", radiusMin: 30, radiusMax: 50}
];
To get the correct settings for a particle (in this case its index) use this function
function getParticleSettings(particleIndex) {
var settingsIndex = Math.floor(particleIndex / 4) % ParticleSettings.length,
settings = ParticleSettings[settingsIndex];
return {
color: settings.color,
radius: getRandom(settings.radiusMin, settings.radiusMax)
};
}
getRandom is just a small helper function to get a random number between two boundaries
function getRandom(min, max) {
return Math.floor((Math.random() * (max - min)) + min)
}
In createParticle we then have to change the for loop to get the settings for the current particle
for (var i = 0; i < QUANTITY; i++) {
// get the settings for the current particle
var particleSettings = getParticleSettings(i);
var particle = {
size: 1,
position: { x: mouseX, y: mouseY },
offset: { x: 0, y: 0 },
shift: { x: mouseX, y: mouseY },
speed: 0.01+Math.random()*0.04,
targetSize: 1,
fillColor: particleSettings.color, // <--
orbit: particleSettings.radius // <--
};
particles.push( particle );
}
This would be the result of the changes above.
You could define the colors in an array since you are using a for loop you can index them like this:
var colors = ['#AAAAAA', '#BBBBBB', '#CCCCCC', '#DDDDDD'];
var particle = {
...
fillColor: colors[i],
...
}
This will now only work for the first four colors, but since you stated you have a quantity of 16, you could use 2 for loops to achieve this. Something like this:
//will run 16 times
for(var i = 0; i < QUANTITY; i++) {
for(var x = 0; x < 4; x++) {
var particle = {
//note that i'm using x here since the array has only 4 keys.
fillColor: colors[x];
}
}
}
I have this piece of code:
var rawData = [20, 20, 20, 20, 20],
data = [
[0, 100]
],
overData = [
[0, 0]
],
underData = [
[0, 0]
],
zones = [],
len = rawData.length,
colors = Highcharts.getOptions().colors,
maxColor = colors.length,
i,
val,
sum = 0,
pos = 0,
plotLines = [];
for (i = 0; i < len; i++) {
sum += rawData[i];
}
for (i = 0; i < len; i++) {
pos += rawData[i];
val = (sum - pos) / sum * 100;
data.push([pos, val]);
overData.push([pos, (100 - val) / 2]);
underData.push([pos, (100 - val) / 2]);
zones.push({
value: pos,
color: colors[i % maxColor]
});
plotLines.push({
zIndex: 7,
width: 3,
color: '#aaa',
value: pos,
label: {
text: rawData[i],
verticalAlign: 'bottom',
rotation: 0,
y: -10,
align: 'right',
x: -12,
style: {
color: colors[i % maxColor],
fontWeight: 'bold'
}
}
});
}
Now this line seems to use the API to generate standard highcharts colors:
colors = Highcharts.getOptions().colors
How can I set a color I define for each "zone"? Could you please show me a small sample of how I could achieve a color for each zone?
Thanks