I am using chart.js v2.5.0.
I put doughnut inside doughnut.
I want the disdance between 2 doughnuts(A) to be larger without affecting the distance between slices inside the same doughnut(B).
Please see the following image:
Currently I am using the property borderWidth.
However, this also affects the width of B.
Please see the following code:
options: {
elements: {
arc: {
borderWidth: 18,
},
},
cutoutPercentage: 60,
responsive: true,
}
I want the doughnuts to look like this:
The only way to achieve this is to extend the existing doughnut controller and overwrite the update method with your own logic for determining the spacing.
Here is an example demonstrating how you would do this. With this implementation, I added a new doughnut chart option property called datasetRadiusBuffer that controls the white space between each dataset.
var helpers = Chart.helpers;
// this option will control the white space between embedded charts when there is more than 1 dataset
helpers.extend(Chart.defaults.doughnut, {
datasetRadiusBuffer: 0
});
Chart.controllers.doughnut = Chart.controllers.doughnut.extend({
update: function(reset) {
var me = this;
var chart = me.chart,
chartArea = chart.chartArea,
opts = chart.options,
arcOpts = opts.elements.arc,
availableWidth = chartArea.right - chartArea.left - arcOpts.borderWidth,
availableHeight = chartArea.bottom - chartArea.top - arcOpts.borderWidth,
minSize = Math.min(availableWidth, availableHeight),
offset = {
x: 0,
y: 0
},
meta = me.getMeta(),
cutoutPercentage = opts.cutoutPercentage,
circumference = opts.circumference;
// If the chart's circumference isn't a full circle, calculate minSize as a ratio of the width/height of the arc
if (circumference < Math.PI * 2.0) {
var startAngle = opts.rotation % (Math.PI * 2.0);
startAngle += Math.PI * 2.0 * (startAngle >= Math.PI ? -1 : startAngle < -Math.PI ? 1 : 0);
var endAngle = startAngle + circumference;
var start = {x: Math.cos(startAngle), y: Math.sin(startAngle)};
var end = {x: Math.cos(endAngle), y: Math.sin(endAngle)};
var contains0 = (startAngle <= 0 && 0 <= endAngle) || (startAngle <= Math.PI * 2.0 && Math.PI * 2.0 <= endAngle);
var contains90 = (startAngle <= Math.PI * 0.5 && Math.PI * 0.5 <= endAngle) || (startAngle <= Math.PI * 2.5 && Math.PI * 2.5 <= endAngle);
var contains180 = (startAngle <= -Math.PI && -Math.PI <= endAngle) || (startAngle <= Math.PI && Math.PI <= endAngle);
var contains270 = (startAngle <= -Math.PI * 0.5 && -Math.PI * 0.5 <= endAngle) || (startAngle <= Math.PI * 1.5 && Math.PI * 1.5 <= endAngle);
var cutout = cutoutPercentage / 100.0;
var min = {x: contains180 ? -1 : Math.min(start.x * (start.x < 0 ? 1 : cutout), end.x * (end.x < 0 ? 1 : cutout)), y: contains270 ? -1 : Math.min(start.y * (start.y < 0 ? 1 : cutout), end.y * (end.y < 0 ? 1 : cutout))};
var max = {x: contains0 ? 1 : Math.max(start.x * (start.x > 0 ? 1 : cutout), end.x * (end.x > 0 ? 1 : cutout)), y: contains90 ? 1 : Math.max(start.y * (start.y > 0 ? 1 : cutout), end.y * (end.y > 0 ? 1 : cutout))};
var size = {width: (max.x - min.x) * 0.5, height: (max.y - min.y) * 0.5};
minSize = Math.min(availableWidth / size.width, availableHeight / size.height);
offset = {x: (max.x + min.x) * -0.5, y: (max.y + min.y) * -0.5};
}
chart.borderWidth = me.getMaxBorderWidth(meta.data);
chart.outerRadius = Math.max((minSize - chart.borderWidth) / 2, 0);
chart.innerRadius = Math.max(cutoutPercentage ? (chart.outerRadius / 100) * (cutoutPercentage) : 0, 0);
chart.radiusLength = ((chart.outerRadius - chart.innerRadius) / chart.getVisibleDatasetCount()) + 25;
chart.offsetX = offset.x * chart.outerRadius;
chart.offsetY = offset.y * chart.outerRadius;
meta.total = me.calculateTotal();
me.outerRadius = chart.outerRadius - (chart.radiusLength * me.getRingIndex(me.index));
me.innerRadius = Math.max(me.outerRadius - chart.radiusLength, 0);
// factor in the radius buffer if the chart has more than 1 dataset
if (me.index > 0) {
me.outerRadius -= opts.datasetRadiusBuffer;
me.innerRadius -= opts.datasetRadiusBuffer;
}
helpers.each(meta.data, function(arc, index) {
me.updateElement(arc, index, reset);
});
},
});
You can see a live example at this codepen.
To make it work with the latest ChartJS 2.7.2, I've just copied the source as suggested from https://github.com/chartjs/Chart.js/blob/master/src/controllers/controller.doughnut.js. Then I added the patch:
if (me.index > 0) {
me.outerRadius -= opts.datasetRadiusBuffer;
me.innerRadius -= opts.datasetRadiusBuffer;
}
Everything was working as expected.
Picture of 3 datasets in doughnut chart with "padding"
I achieved this by inserting a transparent dataset between the colored datasets. Didn't find another "easy" way.
In the end it was easier to do the whole chart myself instead of using chartjs.
Another solution here : Padding Between Pie Charts in chart js
const colors = ["#FF6384", "#36A2EB", "#FFCE56"];
var pieChart = new Chart("myChart", {
type: 'pie',
data: {
labels: ["Red", "Blue", "Yellow"],
datasets: [{
data: [8, 5, 6],
backgroundColor: colors,
},{
weight: 0.2
},{
data: [5, 7, 4],
backgroundColor: colors,
weight: 1.2
}]
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart"></canvas>
Related
I have the following SVG element which was created using JS: https://akzhy.com/blog/create-animated-donut-chart-using-svg-and-javascript
<div class="doughnut">
<svg width="100%" height="100%" viewBox="0 0 100 100">
<circle cx="50" cy="50" r="30" stroke="#80e080" stroke-width="15" fill="transparent" stroke-dasharray="188.496" stroke-dashoffset="141.372" transform='rotate(-90 50 50)'/>
<circle cx="50" cy="50" r="30" stroke="#4fc3f7" stroke-width="15" fill="transparent" stroke-dasharray="188.496" stroke-dashoffset="103.6728" transform='rotate(0 50 50)'/>
<circle cx="50" cy="50" r="30" stroke="#9575cd" stroke-width="15" fill="transparent" stroke-dasharray="188.496" stroke-dashoffset="169.6464" transform='rotate(162 50 50)'/>
<circle cx="50" cy="50" r="30" stroke="#f06292" stroke-width="15" fill="transparent" stroke-dasharray="188.496" stroke-dashoffset="150.7968" transform='rotate(198 50 50)'/>
</svg>
</div>
Is it possible to to get a path from the svg node?
Conversion via graphic app
Open you svg in an application like Illustrator/inkscape etc.
You could use path operations like "stroke-to-path" to convert stroke based chart segments (the visual colored segments are just dashed strokes applied to a full circle).
Use a pie/donut generator script returning solid paths
Based on this answer by #ray hatfield Pie chart using circle element you can calculate d properties based on the arc command.
Example json based pie chart generator
let pies = document.querySelectorAll('.pie-generate');
generatePies(pies);
function generatePies(pies) {
if (pies.length) {
pies.forEach(function(pie, i) {
let data = pie.getAttribute('data-pie');
if (data) {
data = JSON.parse(data);
w = data['width'];
h = data['height'];
let svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svg.setAttribute('viewBox', '0 0 ' + w + ' ' + h);
svg.setAttribute('width', w);
svg.setAttribute('height', h);
svg.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
pie.appendChild(svg);
addSegments(svg, data);
}
})
}
}
function addSegments(svg, data) {
let segments = data["segments"];
let strokeWidth = data["strokeWidth"];
let centerX = data["centerX"];
let centerY = data["centerY"];
let radius = data["radius"];
let startingAngle = (data["startingAngle"] || data["startingAngle"] == 0) ? data["startingAngle"] : -90;
let gap = data["gap"];
let decimals = data["decimals"];
let offset = 0;
let output = "";
// calculate auto percentages
let total = 0;
let calc = data["calc"] ? true : false;
if (calc) {
segments.forEach(function(segment, i) {
total += segment[0];
});
}
// prevent too large gaps
let circumference = Math.PI * radius * 2;
let circumferencePerc = (circumference / 100);
let gapPercentOuter = 100 / circumference * gap;
if (gapPercentOuter > circumferencePerc) {
gap = gap / (gapPercentOuter / circumferencePerc)
}
segments.forEach(function(segment, i) {
let percent = segment[0];
// calc percentages
let percentCalc = percent.toString().indexOf('/') != -1 ? segment[0].split('/') : [];
percent = percentCalc.length ? percentCalc[0] / percentCalc[1] * 100 : +percent
// calculate auto percentages to get 100% in total
if (total) {
percent = 100 / total * percent;
}
let percentRound = percent.toFixed(decimals);
// auto fill color
let segOptions = segment[1] ? segment[1] : '';
let fill = segOptions ? 'fill="' + segOptions['color'] + '"' : "";
if (!fill) {
let hueCut = 0;
let hueShift = 0;
let hue = Math.abs((360 - hueCut) / 100 * (offset + percent)) + hueShift;
let autoColor = hslToHex(hue.toFixed(0) * 1, 60, 50);
fill = 'fill="' + autoColor + '"';
}
let className = segOptions['class'] ? segOptions['class'] : "";
let classPercent = percentRound.toString().replaceAll('.', '_');
let id = segOptions['id'] ? 'id="' + segOptions['id'] + '" ' : '';
let d = getArcD(centerX, centerY, strokeWidth, offset, percent, radius, gap, decimals, startingAngle);
output +=
`\n<path d="${d}" ${fill} class="segment segment-${classPercent} segment-${(i+1)} ${className}" ${id} data-percent="${percentRound}"/>`;
offset += percent;
});
svg.innerHTML = output;
}
function getArcD(centerX, centerY, strokeWidth, percentStart, percent, radiusOuter, gap, decimals = 3, startingAngle = -90) {
let radiusInner = radiusOuter - strokeWidth;
let circumference = Math.PI * radiusOuter * 2;
let isPieChart = false;
// if pie chart – stroke equals radius
if (strokeWidth + gap >= radiusOuter) {
isPieChart = true;
}
let circumferenceInner = Math.PI * radiusInner * 2;
let gapPercentOuter = ((100 / circumference) * gap) / 2;
let gapPercentInner = ((100 / circumferenceInner) * gap) / 2;
//add offset from previous segments
percentStart = percentStart;
let percentEnd = percent + percentStart;
// outer coordinates
let [x1, y1] = getPosOnCircle(centerX, centerY, (percentStart + gapPercentOuter), radiusOuter, decimals, startingAngle);
let [x2, y2] = getPosOnCircle(centerX, centerY, percentEnd - gapPercentOuter, radiusOuter, decimals, startingAngle);
// switch arc output between long or short arc segment according to percentage
let longArc = percent >= 50 ? 1 : 0;
let rotation = 0;
let clockwise = 1;
let counterclockwise = 0;
let d = '';
// if donut chart
if (!isPieChart) {
//inner coordinates
let [x3, y3] = getPosOnCircle(centerX, centerY, percentEnd - gapPercentInner, radiusInner, decimals, startingAngle);
let [x4, y4] = getPosOnCircle(centerX, centerY, percentStart + gapPercentInner, radiusInner, decimals, startingAngle);
d = [
"M", x1, y1,
"A", radiusOuter, radiusOuter, rotation, longArc, clockwise, x2, y2,
"L", x3, y3,
"A", radiusInner, radiusInner, rotation, longArc, counterclockwise, x4, y4,
"z"
];
}
// if pie chart – stroke equals radius: drop inner radius arc
else {
// find opposite coordinates
let [x1o, y1o] = getPosOnCircle(centerX, centerY, (percentStart - gapPercentOuter) - 50, radiusOuter, decimals, startingAngle);
let [x2o, y2o] = getPosOnCircle(centerX, centerY, (percentEnd + gapPercentOuter) - 50, radiusOuter, decimals, startingAngle);
let extrapolatedIntersection = getLinesIntersection(
[x1, y1, x1o, y1o], [x2, y2, x2o, y2o],
decimals);
d = [
"M", x1, y1,
"A", radiusOuter, radiusOuter, rotation, longArc, clockwise, x2, y2,
"L", extrapolatedIntersection.join(" "),
"z"
];
}
return d.join(" ");
}
// helper: get x/y coordinates according to angle percentage
function getPosOnCircle(centerX, centerY, percent, radius, decimals = 3, angleOffset = -90) {
let angle = 360 / (100 / percent) + angleOffset;
let x = +(centerX + Math.cos((angle * Math.PI) / 180) * radius).toFixed(
decimals
);
let y = +(centerY + Math.sin((angle * Math.PI) / 180) * radius).toFixed(
decimals
);
return [x, y];
}
// helper: get intersection coordinates
function getLinesIntersection(l1, l2, decimals = 3) {
let intersection = [];
let c2x = l2[0] - l2[2];
let c3x = l1[0] - l1[2];
let c2y = l2[1] - l2[3];
let c3y = l1[1] - l1[3];
// down part of intersection point formula
let d = c3x * c2y - c3y * c2x;
if (d != 0) {
// upper part of intersection point formula
let u1 = l1[0] * l1[3] - l1[1] * l1[2];
let u4 = l2[0] * l2[3] - l2[1] * l2[2];
// intersection point formula
let px = +((u1 * c2x - c3x * u4) / d).toFixed(decimals);
let py = +((u1 * c2y - c3y * u4) / d).toFixed(decimals);
intersection = [px, py];
}
return intersection;
}
function hslToHex(h, s, l) {
l /= 100;
const a = s * Math.min(l, 1 - l) / 100;
const f = n => {
const k = (n + h / 30) % 12;
const color = l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);
return Math.round(255 * color).toString(16).padStart(2, '0'); // convert to Hex and prefix "0" if needed
};
return `#${f(0)}${f(8)}${f(4)}`;
}
<div class="pie-generate" data-pie='{
"width": 100,
"height": 100,
"radius": 50,
"centerX": 50,
"centerY": 50,
"strokeWidth": 20,
"gap": 0,
"decimals": 3,
"segments": [
["25", {"color":"#80e080", "id":"seg01", "class":"segCustom"}],
["45", {"color":"#4fc3f7", "id":"seg02", "class":"segCustom"}],
["10", {"color":"#9575cd", "id":"seg03", "class":"segCustom"}],
["20", {"color":"#f06292", "id":"seg04", "class":"segCustom"}]
]
}'>
</div>
You can tweak different segment percentages by changing the JSOn data-attribute.
<div class="pie-generate" data-pie='{
"width": 100,
"height": 100,
"radius": 50,
"centerX": 50,
"centerY": 50,
"strokeWidth": 20,
"gap": 0,
"decimals": 3,
"segments": [
["25", {"color":"#80e080", "id":"seg01", "class":"segCustom"}],
["45", {"color":"#4fc3f7", "id":"seg02", "class":"segCustom"}],
["10", {"color":"#9575cd", "id":"seg03", "class":"segCustom"}],
["20", {"color":"#f06292", "id":"seg04", "class":"segCustom"}]
]
}'>
</div>
Segment output:
<path d="M 50 0 A 50 50 0 0 1 100 50 L 80 50 A 30 30 0 0 0 50 20 z" fill="#80e080" />
I'm trying to zoom at mouse position, like say on google maps. It kind of works but it shifts the point i want to zoom in on wherever it matches up with the original.Then when i zoom at that point it works fine. I think I need to translate the point back to the mouse, but I'm not sure how to do it exactly.
This is the code before i draw:
translate(zoomLocation.x, zoomLocation.y);
scale(zoom);
translate(-zoomLocation.x, -zoomLocation.y);
drawGrid();
And this is when I zoom:
event.preventDefault();
zoomLocation = {
x: zoomLocation.x + (mouseX - zoomLocation.x) / zoom,
y: zoomLocation.y + (mouseY - zoomLocation.y) / zoom
};
zoom -= zoomSensitivity * event.delta;
let colors = {
background: 0,
gridLines: "white"
};
let nVariables = 4;
let zoom = 1;
let zoomLocation = {
x: 0,
y: 0
};
let zoomSensitivity = 0.0002;
function draw() {
translate(zoomLocation.x, zoomLocation.y);
scale(zoom);
translate(-zoomLocation.x, -zoomLocation.y);
drawGrid();
stroke("blue");
ellipse(zoomLocation.x + (mouseX - zoomLocation.x) / zoom, zoomLocation.y + (mouseY - zoomLocation.y) / zoom, 10, 10);
stroke("red");
ellipse(zoomLocation.x, zoomLocation.y, 10, 10);
}
function setup() {
zoomLocation = {
x: 0,
y: windowHeight / 2
}
createCanvas(windowWidth, windowHeight);
}
function mouseWheel(event) {
event.preventDefault();
let oldZoom = zoom;
zoomLocation = {
x: zoomLocation.x + (mouseX - zoomLocation.x) / zoom,
y: zoomLocation.y + (mouseY - zoomLocation.y) / zoom
};
zoom -= zoomSensitivity * event.delta;
}
function drawGrid() {
let nCells = 2 ** nVariables;
if (nCells > 2048) {
if (!window.confirm(`You are about to create ${nCells} cells. This might lag your browser. Are you sure?`)) {
return;
}
}
background(colors.background);
let gridWidth = windowWidth - 2;
let gridHeight = min(gridWidth / nCells, windowHeight / 2 - 2);
let gridY = windowHeight / 2;
stroke(colors.gridLines);
line(0, gridY, gridWidth, gridY);
line(0, gridY + gridHeight, gridWidth, gridY + gridHeight);
for (let i = 0; i < nCells + 1; i++) {
line(i * (gridWidth / nCells), gridY, i * (gridWidth / nCells), gridY + gridHeight)
}
let curveHeight = 2;
let drawVariable = (n) => {
let p1 = {
x: 1 / (2 ** (n + 1)) * gridWidth,
y: gridY
};
let c1 = {
x: p1.x,
y: p1.y + gridWidth / (2 ** n) * curveHeight
};
let p2 = {
y: p1.y
};
let c2 = {
y: c1.y
};;
noFill();
stroke("red");
if (n == 0) {
p2.x = gridWidth;
c2.x = p2.x;
c1.y = c2.y = p1.y + gridWidth / 2 * curveHeight;
curve(c1.x, c1.y, p1.x, p1.y, p2.x, p2.y, c2.x, c2.y);
return;
}
for (let i = 3; i < 2 ** (n + 1); i += 2) {
p2.x = i / (2 ** (n + 1)) * gridWidth
c2.x = p2.x;
if ((i - 3) % 4 == 0) {
curve(c1.x, c1.y, p1.x, p1.y, p2.x, p2.y, c2.x, c2.y);
} else {
p1.x = p2.x;
c1.x = c2.x;
}
}
};
for (let i = 0; i < nVariables; i++) {
drawVariable(i);
}
}
body {
margin: 0
}
button {
outline: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.11/p5.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.11/addons/p5.dom.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
What you're looking for is an application of Affine Transformation. Here's an example where I'm applying transformations incrementally to transform + scale at the mouse pointer location for a Google Maps type zoom effect: Zoom Effect in p5.js Web Editor.
This is a good medium article that explains why this works: Zooming at the Mouse Coordinates with Affine Transformations
This is another good article that has some mathematical explanations on how it achieves the effects: Affine Transformations — Pan, Zoom, Skew
am very new to raphael js so and kind of in a hurry to find how how i can draw a poly shape with dracula graph. This will have to go in a costum renderer such as:
var render = function(r, n) {
/* the Raphael set is obligatory, containing all you want to display */
var set = r.set().push(
/* custom objects go here */
r.rect(n.point[0]-30, n.point[1]-13, 62, 86)
.attr({"fill": "#fa8", "stroke-width": 2, r : "9px"}))
.push(r.text(n.point[0], n.point[1] + 30, n.label)
.attr({"font-size":"20px"}));
/* custom tooltip attached to the set */
set.items.forEach(
function(el) {
el.tooltip(r.set().push(r.rect(0, 0, 30, 30)
.attr({"fill": "#fec", "stroke-width": 1, r : "9px"})))});
return set;
};
If anybody has dealt with such would love the help.
This solved! Found it on Raphael js by chris wilson
var paper = Raphael(0, 0, 500, 500);
function NGon(x, y, N, side, angle) {
paper.circle(x, y, 3).attr("fill", "black");
var path = "",
c, temp_x, temp_y, theta;
for (c = 0; c <= N; c += 1) {
theta = (c + 0.5) / N * 2 * Math.PI;
temp_x = x + Math.cos(theta) * side;
temp_y = y + Math.sin(theta) * side;
path += (c === 0 ? "M" : "L") + temp_x + "," + temp_y;
}
return path;
}
paper.path(NGon(050, 50, 8, 40));
I've modified this example of inverse kinematics in JavaScript with HTML5 Canvas and made it dynamic by seperating it into a function, and it works, but the example only uses 3 points -- start, middle, and end, and I'd like to change the number of points at will. Here's my current fiddle...
function _kinematics(joints, fx, mouse) {
joints.forEach(function (joint) {
joint.target = joint.target || {
x: fx.canvas.width / 2,
y: fx.canvas.height / 2
};
joint.start = joint.start || {
x: 0,
y: 0
};
joint.middle = joint.middle || {
x: 0,
y: 0
};
joint.end = joint.end || {
x: 0,
y: 0
};
joint.length = joint.length || 50;
});
var theta,
$theta,
_theta,
dx,
dy,
distance;
joints.forEach(function (joint) {
if (mouse) {
joint.target.x = mouse.x;
joint.target.y = mouse.y;
}
dx = joint.target.x - joint.start.x;
dy = joint.target.y - joint.start.y;
distance = Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
_theta = Math.atan2(dy, dx);
if (distance < joint.length) {
theta = Math.acos(distance / (joint.length + joint.length)) + _theta;
dx = dx - joint.length * Math.cos(theta);
dy = dy - joint.length * Math.sin(theta);
$theta = Math.atan2(dy, dx);
} else {
theta = $theta = _theta;
}
joint.middle.x = joint.start.x + Math.cos(theta) * joint.length;
joint.middle.y = joint.start.y + Math.sin(theta) * joint.length;
joint.end.x = joint.middle.x + Math.cos($theta) * joint.length;
joint.end.y = joint.middle.y + Math.sin($theta) * joint.length;
fx.beginPath();
fx.moveTo(joint.start.x, joint.start.y);
/* for (var i = 0; i < joint.points.length / 2; i++) {
fx.lineTo(joint.points[i].x, joint.points[i].y);
} */
fx.lineTo(joint.middle.x, joint.middle.y);
/* for (var j = joint.points.length / 2; j < joint.points.length; j++) {
fx.lineTo(joint.points[j].x, joint.points[j].y);
} */
fx.lineTo(joint.end.x, joint.end.y);
fx.strokeStyle = "rgba(0,0,0,0.5)";
fx.stroke();
fx.beginPath();
fx.arc(joint.start.x, joint.start.y, 10, 0, Math.PI * 2);
fx.fillStyle = "rgba(255,0,0,0.5)";
fx.fill();
fx.beginPath();
fx.arc(joint.middle.x, joint.middle.y, 10, 0, Math.PI * 2);
fx.fillStyle = "rgba(0,255,0,0.5)";
fx.fill();
fx.beginPath();
fx.arc(joint.end.x, joint.end.y, 10, 0, Math.PI * 2);
fx.fillStyle = "rgba(0,0,255,0.5)";
fx.fill();
});
}
That's just the function, I've omitted the rest for brevity. As you can see, the commented-out lines were my attempt to draw the other points.
Also, here's where I populate the joints array with the points and such. See commented lines.
populate(_joints, $joints, function() {
var coords = randCoords(map);
var o = {
start: {
x: coords.x,
y: coords.y
},
// points: [],
target: {
x: mouse.x,
y: mouse.y
}
};
/* for (var p = 0; p < 10; p++) {
o.points.push({
x: p === 0 ? o.start.x + (o.length || 50) : o.points[p - 1].x + (o.length || 50),
y: p === 0 ? o.start.y + (o.length || 50) : o.points[p - 1].y + (o.length || 50)
});
}; */
return o;
});
How would I make this function work with n points?
is possible to create a circle with raphael with conical gradient?
Something like colorwheel of http://raphaeljs.com/picker/ but with customized colors
ex: "from red to orange to yellow to green to yellow to orange to red)"
Yes it is, try this function (I statred from Raphael's Colorpicker code, made it stand-alone and added the gradation between specific colors instead of just increasing the hue along the disc):
var paper = Raphael('paper', 800, 600);
var wheel = function (x, y, r, colors) {
var pi = Math.PI;
var nbColors = colors.length;
// Formatting every color to its RGB values
for (var i = 0 ; i < nbColors ; i++)
{
colors[i] = Raphael.getRGB(colors[i]);
}
// Initialize segments
var segments = pi * r * 2 / Math.min(r / 8, 4);
var a = pi / 2 - pi * 2 / segments * 1.5;
var path = ["M", x, y - r, "A", r, r, 0, 0, 1, r * Math.cos(a) + x, y - r * Math.sin(a), "L", x, y, "z"].join();
// Draw segments
for (var i = 0 ; i < segments ; i++)
{
// Between which 2 colors is this segment?
var j = nbColors * i / segments;
var n = Math.floor(j);
var d = j % 1;
var color1 = colors[n];
var color2 = colors[(n + 1) % nbColors];
// Calculate the segment's color from the 2 other
var color =
{ r : Math.round(d * (color2.r - color1.r) + color1.r)
, g : Math.round(d * (color2.g - color1.g) + color1.g)
, b : Math.round(d * (color2.b - color1.b) + color1.b)
}
// Draw the sector
paper.path(path).attr(
{ stroke: 'none'
, fill: 'rgb(' + color.r + ',' + color.g + ',' + color.b + ')'
, rotation: [90 + (360 / segments) * i, x, y]
});
}
// Surrounding circle
return paper.circle(x, y, r).attr(
{ stroke : '#fff'
, 'stroke-width' : Math.round(r * .03)
});
};
You can use it like this, the 4th parameter being an array of colors to use:
wheel (100, 100, 50, ['#F00', '#0FF', '#00F', '#0F0', '#F80']);
wheel (500, 200, 50, ['rgb(255,0,0)', 'hsb(40,100,100)', '#0F00F0']);