After some research and a lot trial and error I wrote following bar chart:
function extractResults(container) {
var results = [];
for (result of container.children) {
var parts = result.innerText.split("-")
results.push(parseInt(parts[1].trim().split(" ")[0]));
}
return results
}
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;
}
Everything is computed based on the canvas height and width, but how should I set them? What value would look good on mobile and desktop devices. I do not use any framework and the html looks like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Results - Is this site great? - easypolls</title>
<link rel="shortcut icon" type="image/x-icon" href="/static/favicon.ico" />
<link rel="stylesheet" type="text/css" href="/static/css/style.css" />
<link rel="stylesheet" type="text/css" href="/static/polls/css/polls.css" />
</head>
<body>
<h2><a href="/">easypolls</a></h2><hr />
<h3>Is this site great?</h3>
<p>04-14-2017 8:05 p.m. (UTC)</p>
<canvas id="chart"><p>Graphs are not supported by this browser.</p></canvas>
<ul id="results">
<li>1.Yes. - 3 votes</li>
<li>2.No. - 0 votes</li>
<li>3.It looks awful! - 1 vote</li>
</ul>
<p><label>Share:<input type="text" value="http://127.0.0.1:8000/1/results/" readonly /></label></p>
<p><label>Embed:<input type="text" value="<iframe src="http://127.0.0.1:8000/1/results/"></iframe>" readonly /></label></p>
<script src="/static/js/shortcuts.js"></script>
<script src="/static/polls/js/results.js"></script>
</body>
</html>