Skip to content

Instantly share code, notes, and snippets.

@isotrope
Created August 23, 2012 12:20
Show Gist options
  • Save isotrope/3436164 to your computer and use it in GitHub Desktop.
Save isotrope/3436164 to your computer and use it in GitHub Desktop.
<h1>Canvas experiment based on tweet</h1>
<p>A simple experiment to generate graphs on the fly</p>
<p>inspired by <a href="https://twitter.com/stephdau/status/238336513170083840">https://twitter.com/stephdau/status/238336513170083840</a>
<form>
<label for="chart_values">Simply enter your values, separated by a + sign</label>
<input id="chart_values" name="chart_values" type="text">
</form>
<div id="debug"></div>
<canvas id="chart1" width="300" height="150"></canvas>
$('form').on('keyup','#chart_values', function() {
var debug_div = $('#debug'),
user_input = $(this).val(),
chart_data = user_input.split('+');
console.log(chart_data);
draw('chart1', chart_data);
});
function draw(id, data) {
var canvas = document.getElementById(id),
ctx = canvas.getContext("2d"),
num_points = data.length,
max_value = Math.max.apply(Math, data),
div_height = $('#' + id).height(),
div_width = $('#' + id).width();
canvas.width = canvas.width;
ctx.beginPath();
ctx.moveTo(0, div_height);
for( var i = 0; i < num_points; i++ ) {
ctx.lineTo(i * div_width / ( num_points - 1 ), div_height - ( div_height * ( data[i] / max_value ) ) );
}
ctx.lineTo(div_width, div_height - ( div_height * ( data[num_points - 1] / max_value ) ) );
ctx.lineTo(div_width, div_height );
ctx.closePath();
ctx.stroke();
ctx.fill();
}
label, input {font-size: 2em; display: block;}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment