Chart.js always visible labels - javascript

I'm reworking a application for a client, and they want to show a chart. They currently use a infragistics chart, and they would love to stop using that, but the layout must remain the same.
this is the layout they want( so labels should be visible, individual bars, ...)
So my first option was to try out Chart.js, but I could only get something like this:
So basicly the only thing that needs to happen is a way to always show the labels.
The data is provided via angular and is just an array if integers. Using the following directive for the chart: http://jtblin.github.io/angular-chart.js/
My current html:
<canvas id="polar" class="chart chart-polar-area" data="data.values" labels="data.labels" width="200" height="200"
options="{animateRotate: false}"></canvas>
I found this; How to add label in chart.js for pie chart but I couldn't get it to work

Based on ChartJS: Change the positions of the tooltips
Preview
Converting the above to angular-chart is easy because we are only setting the options. However we need to make 2 minor changes (i.e. set chart and ctx variables from this
// THIS IS REQUIRED AND WAS ADDED
tooltipEvents: [],
onAnimationComplete: function () {
// THESE 2 LINES ARE NEW
var chart = this.chart;
var ctx = this.chart.ctx;
this.segments.forEach(function (segment) {
var outerEdge = Chart.Arc.prototype.tooltipPosition.apply({
// THESE 2 LINES WERE CHANGED
x: chart.width / 2,
y: chart.height / 2,
startAngle: segment.startAngle,
endAngle: segment.endAngle,
outerRadius: segment.outerRadius * 2 + 10,
innerRadius: 0
})
...
The entire code assuming you have the library scripts included looks something like this
HTML
<div ng-app="myApp">
<div ng-controller="myController">
<canvas id="polar-area" class="chart chart-polar-area" data="data" labels="labels" options="options"></canvas>
</div>
</div>
Script
angular.module('myApp', ["chart.js"]);
angular.module('myApp').controller('myController', function ($scope) {
$scope.labels = ["Download Sales", "In-Store Sales", "Mail-Order Sales", "Tele Sales", "Corporate Sales"];
$scope.data = [300, 500, 100, 40, 120];
$scope.options = {
scaleOverride: true,
scaleStartValue: 0,
scaleStepWidth: 40,
scaleSteps: 10,
tooltipEvents: [],
onAnimationComplete: function () {
var chart = this.chart;
var ctx = this.chart.ctx;
this.segments.forEach(function (segment) {
var outerEdge = Chart.Arc.prototype.tooltipPosition.apply({
x: chart.width / 2,
y: chart.height / 2,
startAngle: segment.startAngle,
endAngle: segment.endAngle,
outerRadius: segment.outerRadius * 2 + 10,
innerRadius: 0
})
var normalizedAngle = (segment.startAngle + segment.endAngle) / 2;
while (normalizedAngle > 2 * Math.PI) {
normalizedAngle -= (2 * Math.PI)
}
if (normalizedAngle < (Math.PI * 0.4) || (normalizedAngle > Math.PI * 1.5))
ctx.textAlign = "start";
else if (normalizedAngle > (Math.PI * 0.4) && (normalizedAngle < Math.PI * 0.6)) {
outerEdge.y += 5;
ctx.textAlign = "center";
}
else if (normalizedAngle > (Math.PI * 1.4) && (normalizedAngle < Math.PI * 1.6)) {
outerEdge.y - 5;
ctx.textAlign = "center";
}
else
ctx.textAlign = "end";
ctx.fillText(segment.label, outerEdge.x, outerEdge.y);
})
}
}
}
);
Fiddle - http://jsfiddle.net/tmzpy7Lt/

Related

How to find X,Y coordinates on Half Doughnut Chart JS react

I've got the doughnut part of the chart complete and the gauge needle. I want to add this circular pointer on the doughnut instead of the needle. I was able to draw the circular pointer but couldn't find the right X,Y coordinates to place the pointer.
Here is the DEMO
Here in the below image, the circle should be placed at the gauge needle pointer
The code I've used is the following for the circular pointer.
const pointer = {
id: "pointer",
afterDatasetsDraw: (chart) => {
const { ctx } = chart;
var data = chart._metasets[0].data[0];
var radius = data.innerRadius + (data.outerRadius - data.innerRadius) / 2;
var centerX = data.x;
var centerY = data.y;
const angle = (180 / 1000) * speed;
// this thing needs to be fixed
var x = centerX + radius * Math.cos(angle * Math.PI);
var y = centerY + radius * Math.sin(angle * Math.PI);
ctx.save();
ctx.beginPath();
ctx.lineWidth = 6;
ctx.arc(x, y, 12, 0, 2 * Math.PI);
ctx.stroke();
ctx.restore();
}
};
Target to achive:
Basically you want 75% of 180 Degrees (because the speed = 75):
const angle = Math.PI * ( speed / 100) + Math.PI;
And than Math.cos and Math.sin expect a radiant value(link to mdn documentation), which you already have, so no multiplication with Math.PI is needed anymore.
var x = centerX + radius * Math.cos( angle );
var y = centerY + radius * Math.sin( angle );
Full working demo (Updated Example, now with animation):
const speed = 75;
let animationAngle = 0;
var pointer = {
id: 'pointer',
defaults:{
percentage: 0,
maxAngle: 0
},
afterDraw: function(chart, args, opt) {
const { ctx } = chart;
var data = chart._metasets[0].data[0];
var radius = data.innerRadius + (data.outerRadius - data.innerRadius) / 2;
var centerX = data.x;
var centerY = data.y;
const angle = (Math.PI * ( speed / 100) * chart.options.plugins.pointer.percentage) + Math.PI;
var x = centerX + radius * Math.cos( angle );
var y = centerY + radius * Math.sin( angle );
ctx.save();
ctx.beginPath();
ctx.lineWidth = 6;
ctx.arc(x, y, 12, 0, 2 * Math.PI);
ctx.stroke();
ctx.restore();
},
}
var options = {
type: 'doughnut',
data: {
datasets: [{
data: [20, 50, 30],
backgroundColor: [
'rgba(231, 76, 60, 1)',
'rgba(255, 164, 46, 1)',
'rgba(46, 204, 113, 1)'
],
borderColor: [
'rgba(255, 255, 255 ,1)',
'rgba(255, 255, 255 ,1)',
'rgba(255, 255, 255 ,1)'
],
borderWidth: 0
}]},
options: {
cutout: 80,
rotation: -90,
circumference: 180,
animation:{
onProgress: function(context){
if(context.initial){
this.options.plugins.pointer.percentage = context.currentStep / context.numSteps;
}
}
},
maintainAspectRatio: false,
legend: { display: false },
plugins:{
tooltip: { enabled: false },
pointer: {currentAngle: 1}
}
},
plugins:[pointer]
}
const chart = document.getElementById('chart1')
new Chart(chart, options);
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<div style="width:500px;height:184px">
<canvas id="chart1" width="500" height="184"></canvas>
<div>

Chart.js v2: space between doughnut inside doughnut

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>

Chart.js change label color

I am using chart.js library to make polar chart but not able to change the color of the label please help me how can I change the color of the label. My chart look like http://headsocial.com:8080/upload/145448587471822e0922d67c9dd6aae46d70bfeef1623.png, but I want to change the color to grey currently it is showing like orange
function show_polar_chart_data1(data, id){
var jsonData = jQuery.parseJSON(data);
var data = [
{
value: jsonData.IDENTITY_Avg,
color: "#8258FA",
highlight: "#8258FA",
label: "IDENTITY("+jsonData.IDENTITY+")"
},
{
value: jsonData.ROLE_Avg,
color: "#34ED13",
highlight: "#34ED13",
label: "ROLE("+jsonData.ROLE+")"
},
{
value: jsonData.ATTITUDE_Avg,
color: "#FFFF00",
highlight: "#FFFF00",
label: "ATTITUDE("+jsonData.ATTITUDE+")"
},
{
value: jsonData.AGILITY_Avg,
color: "#FF0000",
highlight: "#FF0000",
label: "AGILITY("+jsonData.AGILITY+")"
},
{
value: jsonData.FAIRNESS_Avg,
color: "#00FFFF",
highlight: "#00FFFF",
label: "FAIRNESS("+jsonData.FAIRNESS+")"
},
{
value: jsonData.CONFLICT_Avg,
color: "#EE9A4D",
highlight: "#EE9A4D",
label: "CONFLICT("+jsonData.CONFLICT+")"
}
];
var ctx = document.getElementById("chart").getContext("2d");
var polarChart = new Chart(ctx).PolarArea(data, {
scaleOverride: true,
scaleStartValue: 0,
scaleStepWidth: 1,
scaleShowLabels: false,
scaleSteps: 10,
onAnimationComplete: function () {
this.segments.forEach(function (segment) {
var outerEdge = Chart.Arc.prototype.tooltipPosition.apply({
x: this.chart.width / 2,
y: this.chart.height / 2,
startAngle: segment.startAngle,
endAngle: segment.endAngle,
outerRadius: segment.outerRadius * 2 + 10,
innerRadius: 0
})
var normalizedAngle = (segment.startAngle + segment.endAngle) / 2;
while (normalizedAngle > 2 * Math.PI) {
normalizedAngle -= (2 * Math.PI)
}
if (normalizedAngle < (Math.PI * 0.4) || (normalizedAngle > Math.PI * 1.5))
ctx.textAlign = "start";
else if (normalizedAngle > (Math.PI * 0.4) && (normalizedAngle < Math.PI * 0.6)) {
outerEdge.y += 5;
ctx.textAlign = "center";
}
else if (normalizedAngle > (Math.PI * 1.4) && (normalizedAngle < Math.PI * 1.6)) {
outerEdge.y - 5;
ctx.textAlign = "center";
}
else
ctx.textAlign = "end";
ctx.fillText(segment.label, outerEdge.x, outerEdge.y);
})
done();
}
});
});
}
}
Just add
ctx.fillStyle = 'black';
before your ctx.fillText...
Have you tried adding:
scaleFontColor: "<the color you want to add>"
to the chart initialization like this:
var polarChart = new Chart(ctx).PolarArea(data, {
scaleFontColor: "<the color you want to add>"
...
Check this SO answer: Change label font color for a line chart using Chart.js

Javascript multiple circular graphs

Ive made a working circular graph using javascript, and Ive run into a problem.
The script fetches the id of the graph in order to work, but I would like multiple graphs.
So here is my question: How do I make the script compatible with multiple graphs? I tried fetching them by their class but that didnt seem to work.
Here is my code:
var el = document.getElementById('graph'); // get canvas
var options = {
percent: el.getAttribute('data-percent') || 25,
size: el.getAttribute('data-size') || 80,
lineWidth: el.getAttribute('data-line') || 5,
color: el.getAttribute('data-color') || 0,
rotate: el.getAttribute('data-rotate') || 0
}
var canvas = document.createElement('canvas');
var span = document.createElement('span');
span.textContent = options.percent + '%';
if (typeof(G_vmlCanvasManager) !== 'undefined') {
G_vmlCanvasManager.initElement(canvas);
}
var ctx = canvas.getContext('2d');
canvas.width = canvas.height = options.size;
el.appendChild(span);
el.appendChild(canvas);
ctx.translate(options.size / 2, options.size / 2); // change center
ctx.rotate((-1 / 2 + options.rotate / 180) * Math.PI); // rotate -90 deg
var radius = (options.size - options.lineWidth) / 2;
var drawCircle = function(color, lineWidth, percent) {
percent = Math.min(Math.max(0, percent || 1), 1);
ctx.beginPath();
ctx.arc(0, 0, radius, 0, Math.PI * 2 * percent, false);
ctx.strokeStyle = color;
ctx.lineCap = 'butt'; // butt, round or square
ctx.lineWidth = lineWidth
ctx.stroke();
};
drawCircle('#F7F7F7', options.lineWidth, 100 / 100);
drawCircle(options.color, options.lineWidth, options.percent / 100);
And this is the HTML:
<div class="chart" id="graph"
data-percent="92"
data-color="#1EA1FF"
data-size="110" data-line="3">
</div>
Thanks in advance.
You should be able to surround everything with a loop. You need to select all the elements with the same class into an array, then loop through that array. I also suggest setting the "el" variable inside the array, then you don't have to change your code:
var graphs = document.getElementsByClassName("chart");
for(var i = 0; i < graphs.length; i++)
{
var el = graphs[i];
//Now the rest of your code
var options = ...
}
"el" then becomes each element as the loop iterates.

Create circle DIV with dividers using jQuery?

is there any way to create a circle div with dividers/segments using jquery?
basically, somehting like this: jsfiddle
/*
* This jquery plugin is based on this blogpost - http://www.switchonthecode.com/tutorials/creating-a-roulette-wheel-using-html5-canvas
* If you want to know more how it works, please refer to the above tutorial.
*
* #author Roy Yu | iroy2000 [at] gmail.com ( modify, repackage and add new features )
* #description: This jquery plugin will create a spin wheel and let you to add players at run time.
*
*/
(function($){
$.fn.spinwheel = function(options, callback){
var params = $.extend({},$.fn.spinwheel.default_options, options), $that = $(this), ctx = null, colorCache = [],
startAngle = 0, arc = Math.PI / 6, spinTimeout = null, spinArcStart = 10, spinTime = 0, spinTimeTotal = 0, spinAngleStart = 0, pplArray = params.pplArray, pplLength = pplArray.length;
if($.isFunction(options)){
callback = options;
options = {};
}
var methods = {
init: function() {
methods.getContext();
methods.setup();
drawWheel();
},
setup: function() {
$(params.spinTrigger).bind('click', function(e){
e.preventDefault();
methods.spin();
});
$(params.addPplTrigger).bind('click', function(e){
e.preventDefault();
var item = $('<li />').append($(params.joiner).val());
$(params.paricipants).append(item);
methods.updatePanel();
});
},
getContext: function() {
if(ctx !== null)
return ctx;
var canvas = $that[0];
ctx = canvas.getContext("2d");
},
spin: function() {
spinAngleStart = Math.random() * 10 + 10;
spinTime = 0;
spinTimeTotal = Math.random() * 3 + 4 * 1000;
rotateWheel();
},
updatePanel: function() {
var $ppl = $(params.paricipants).children();
pplArray = [];
$ppl.each(function(key, value){
pplArray.push(value.innerHTML);
});
arc = 2 * Math.PI / $ppl.length;
pplLength = $ppl.length;
drawWheel();
}
}
function genHex(){
var colors=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"], color = "", digit = [], i;
for (i=0;i<6;i++){
digit[i]=colors[Math.round(Math.random()*14)];
color = color+digit[i];
}
if($.inArray(color, colorCache) > -1){
genHex();
} else {
colorCache.push('#'+color);
return '#'+color;
}
}
var rotateWheel = function rotateWheel() {
spinTime += 30;
if(spinTime >= spinTimeTotal) {
stopRotateWheel();
return;
}
var spinAngle = spinAngleStart - easeOut(spinTime, 0, spinAngleStart, spinTimeTotal);
startAngle += (spinAngle * Math.PI / 180);
drawWheel();
spinTimeout = setTimeout(rotateWheel, 30);
}
function stopRotateWheel () {
clearTimeout(spinTimeout);
var degrees = startAngle * 180 / Math.PI + 90;
var arcd = arc * 180 / Math.PI;
var index = Math.floor((360 - degrees % 360) / arcd);
ctx.save();
ctx.font = params.resultTextFont;
var text = pplArray[index];
$(params.winnerDiv).html(text).show();
//ctx.fillText(text, 250 - ctx.measureText(text).width / 2, 250 + 10);
ctx.restore();
}
function drawArrow() {
ctx.fillStyle = params.arrowColor;
ctx.beginPath();
ctx.moveTo(250 - 4, 250 - (params.outterRadius + 15));
ctx.lineTo(250 + 4, 250 - (params.outterRadius + 15));
ctx.lineTo(250 + 4, 250 - (params.outterRadius - 15));
ctx.lineTo(250 + 9, 250 - (params.outterRadius - 15));
ctx.lineTo(250 + 0, 250 - (params.outterRadius - 23));
ctx.lineTo(250 - 9, 250 - (params.outterRadius - 15));
ctx.lineTo(250 - 4, 250 - (params.outterRadius - 15));
ctx.lineTo(250 - 4, 250 - (params.outterRadius + 15));
ctx.fill();
}
function drawWheel() {
ctx.strokeStyle = params.wheelBorderColor;
ctx.lineWidth = params.wheelBorderWidth;
ctx.font = params.wheelTextFont;
ctx.clearRect(0,0,500,500);
var text = null, i = 0, totalJoiner = pplLength;
for(i = 0; i < totalJoiner; i++) {
text = pplArray[i];
var angle = startAngle + i * arc;
ctx.fillStyle = colorCache.length > totalJoiner ? colorCache[i] : genHex();
ctx.beginPath();
// ** arc(centerX, centerY, radius, startingAngle, endingAngle, antiClockwise);
ctx.arc(250, 250, params.outterRadius, angle, angle + arc, false);
ctx.arc(250, 250, params.innerRadius, angle + arc, angle, true);
ctx.stroke();
ctx.fill();
ctx.save();
ctx.shadowOffsetX = -1;
ctx.shadowOffsetY = -1;
ctx.shadowBlur = 1;
ctx.shadowColor = params.wheelTextShadowColor;
ctx.fillStyle = params.wheelTextColor;
ctx.translate(250 + Math.cos(angle + arc / 2) * params.textRadius, 250 + Math.sin(angle + arc / 2) * params.textRadius);
ctx.rotate(angle + arc / 2 + Math.PI / 2);
ctx.fillText(text, -ctx.measureText(text).width / 2, 0);
ctx.restore();
ctx.closePath();
}
drawArrow();
}
function easeOut(t, b, c, d) {
var ts = (t/=d)*t;
var tc = ts*t;
return b+c*(tc + -3*ts + 3*t);
}
methods.init.apply(this,[]);
}
/* --- please look at the index.html source in order to understand what they do ---
* outterRadius : the big circle border
* innerRadius : the inner circle border
* textRadius : How far the the text on the wheel locate from the center point
* spinTrigger : the element that trigger the spin action
* wheelBorderColor : what is the wheel border color
* wheelBorderWidth : what is the "thickness" of the border of the wheel
* wheelTextFont : what is the style of the text on the wheel
* wheelTextColor : what is the color of the tet on the wheel
* wheelTextShadow : what is the shadow for the text on the wheel
* resultTextFont : it is not being used currently
* arrowColor : what is the color of the arrow on the top
* participants : what is the container for participants for the wheel
* joiner : usually a form input where user can put in their name
* addPplTrigger : what element will trigger the add participant
* winDiv : the element you want to display the winner
*/
$.fn.spinwheel.default_options = {
outterRadius:200, innerRadius:3, textRadius: 160, spinTrigger: '.spin-trigger',
wheelBorderColor: 'black',wheelBorderWidth : 3, wheelTextFont : 'bold 15px sans-serif', wheelTextColor: 'black', wheelTextShadowColor : 'rgb(220,220,220)',
resultTextFont : 'bold 30px sans-serif', arrowColor :'black', paricipants:'.participants', addPplTrigger:'.add', joiner:'.joiner', winnerDiv:'.winner'
}
})(jQuery);
$(document).ready(function(){
$('.canvas').spinwheel({
pplArray : ["♈", "♉", "♊", "♋","♌", "♍", "♎", "♏","♐", "♑", "♒", "♓"]
});
});
#main {
width:1000px;
}
#left-column {
float:left;
width:600px;
padding-right:15px;
}
#right-column {
float:right;
width:300px;
}
.participants {
list-style:none;
}
.participants li {
border-radius:15px;
padding:15px;
font-family: 'Carter One', arial, serif;
font-size:150%;
text-shadow: 2px 2px 2px #000;
}
.participants li:nth-child(2n+1) {
background-color:#bada55;
}
.winner {
font-family: 'Carter One', arial, serif;
font-size:250%;
text-shadow: 2px 2px 2px #000;
display:none;
}
.winner:before {
content: "The Winner is ... "
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
<div id="main">
<div id="left-column">
<form class="iform" action="#" method="get">
<label for="joiner"></label>
<input id="joiner" name="joiner" class="joiner" placeholder="Please Enter your name" />
<button class="add">Add</button>
<button class="spin-trigger">Spin</button>
</form>
<canvas class="canvas" width="500" height="500"></canvas>
</div>
<div id="right-column">
<p class="winner">The Winner is ... <span> </span></p>
<ul class="participants">
</ul>
</div>
<div style="clear:both"></div>
</div>
I can use the code above but it is HTML5 and I'm trying to keep clear of the HTML5 in my project so it would be great to do this using Jquery as it will give me more freedom in terms of using external images and I wont have to fiddle about with canvas and all that in html5.
I just need to create a the circle div and divide based on the users input and let the users to choose the background colour on each segment>
I did try this with the code above in jsfiddle and I can let the user to even choose the background colour of the segment but there are some bugs which led me to think its best to use jquery.
example based on the code in jsfiddle above:
for (i=0;i<1;i++){
digit[i]=colors[Math.round(Math.random()*1)];
//color = color+digit[i];
color = document.getElementById("colour").value;
//color = color+digit[i];
}
any advise would be greatly appreciated.
EDIT:
I am trying to modify the code bellow.
basically, what i am trying to do is to let the users to choose the colours of segments.
this is the original jsfiddle: http://jsfiddle.net/kYvzd/118/light/
so what i've done so far is this:
edited the HTML and added this to it:
<select id="colour" name="colour" class="colour">
<option value=""></option>
<option value="db0000">Red</option>
<option value="171515">Black</option>
<option value="008c0a">Green</option>
</select>
edited the javascript and added this:
for (i=0;i<1;i++){
digit[i]=colors[Math.round(Math.random()*1)];
//color = color+digit[i];
color = document.getElementById("colour").value;
//color = color+digit[i];
}
the issue that I am facing right now is very strange.
basically with my edit, it will add the segments but it doesn't add the colours properly! it will add the 1st segment with its colour properly, it will add the 2nd segment with its colour properly too and the issue starts from adding the third segment... it will add the segment but it will not add the colour properly! it will jump back to the previous background colour for the previous segment!
could someone please advise on this issue?
This library looks pretty good:
http://www.openstudio.fr/lab/Library-for-simple-drawing-with.html?lang=fr
$("#example3").fillArc(0, 0, 100, 45, 260, {color: '#ffa500'})
.fillArc(0, 0, 100, 260, 310, {color: '#00c7ee'})
.fillArc(0, 0, 100, 310, 45, {color: '#46aa08'});

Categories