Created
August 23, 2012 12:20
-
-
Save isotrope/3436164 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$('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(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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