以下代码是我尝试使用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}]
问题是:
答案 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;
}