在javascript中的条形图

时间:2017-04-15 20:14:30

标签: javascript html5 charts html5-canvas

以下代码是我尝试使用javascript和html 5画布创建条形图:

var canvas = $("#chart");
var ctx = canvas.getContext("2d");
ctx.strokeFill = "green";
var margin = 5;
var bWidth = (canvas.width - (margin * results.length)) / results.length;
var max = results.sort()[results.length - 1];
var yScale = canvas.height / max;
for (result of results)
{
    ctx.strokeRect();
}

我试图想象的数据如下所示:

[{"choice": "Yes", votes: 2}, {"choice": "No", votes: 1}, {"choice":"maybe", votes: 3}]

问题是:

  • 如何计算每个元素的x和y轴?
  • 如何在条形图下打印选项?
  • 最多可以有20个选项,每个选项最多可以包含200个字符。怎么办呢?

1 个答案:

答案 0 :(得分:0)

经过进一步研究后,以下是解决方案:

var results = extractResults($("#results"));
var canvas = $("#chart");
var ctx = canvas.getContext("2d");
var margin = canvas.width * 0.005;
var bWidth = (canvas.width - (margin * results.length)) / results.length;
var max = Math.max.apply( Math, results );
var yScale = canvas.height / max;
var currX = margin;
ctx.font = "20px Arial"
for (i = 0; i < results.length; i++)
{
    var bHeight = yScale * results[i];
    ctx.fillStyle = "green";
    ctx.fillRect(currX, canvas.height - bHeight, bWidth, bHeight);
    ctx.fillStyle = "black";
    ctx.fillText(i + 1, currX + bWidth / 2, canvas.height - canvas.height * 0.05, bWidth / 2);
    currX += bWidth + margin;
}