I have a poll system and I want answers for this poll to be colored. For example: If it\'s 10% it would be red, if 40% it would be yellow and if 80% it would be green, so I
I know this is kind of bump to topic but I found one more way of doing it.
To do this you can also create a dynamic canvas of 100x1 dimension and apply gradient to it and then from function you just need to get pixel color of the percent location.
Here is the code : This is global:
/* dynamic canvas */
// this should be done once in a page so out of function, makes function faster
var colorBook = $('')[0];
colorBook.width = 101;
colorBook.height = 1;
var ctx = colorBook.getContext("2d");
var grd = ctx.createLinearGradient(0, 0, 101, 0);
grd.addColorStop(0, "rgb(255,0,0)"); //red
grd.addColorStop(0.5, "rgb(255,255,0)"); //yellow
grd.addColorStop(1, "rgb(0,255,0)"); //green
ctx.fillStyle = grd;
ctx.fillRect(0, 0, 101, 1);
Then the function:
function getColor(value) {
return 'rgba(' + ctx.getImageData(Math.round(value), 0, 1, 1).data.join() + ')';
}
Demo : https://jsfiddle.net/asu09csj/