Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Plotting math functions with Canvas-HTML5
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div>
<canvas id="canvas" height="300px" width="500px">
Your browser doesn't support canvas
</canvas>
</div>
</body>
<script src="index.js"></script>
<script type="text/javascript">
var xExists = [0, 2*Math.PI],
fn = function(x) {
return Math.sin(x) * Math.cos(2*x)/2;
};
migs.plot(fn, xExists);
</script>
</html>
var migs = (function (){
//
//Declare global variables
var canvas = document.getElementById("canvas"),
context,
points = [],
t,
f,
width,
height,
xstart,
ystart,
_xscale,
_yscale,
xreal,
yreal,
x0,
x1,
y0,
y1,
xorigin;
var lineSettings = function(){
context.strokeStyle = 'red';
context.lineWidth = 2;
context.stroke();
}
//
//Draw points in canvas context
var draw = function () {
if (t < points.length - 1) {
requestAnimationFrame(draw);
}
if(points[t] !== undefined) {
context.beginPath();
context.moveTo(points[t - 1].x + 0.5, points[t - 1].y + 0.5);
context.lineTo(points[t].x + 0.5, points[t].y + 0.5);
lineSettings();
t++;
}
};
//
//Evaluate f(x) and set points
var eval = function () {
for (var x = xstart; x < width; x++) {
xreal = (x / (xorigin)) - x0,
yreal = height - ((f(xreal) - y0) * _yscale);
ystart = (x === xstart) ? yreal : ystart;
points.push({ x: x, y: yreal });
}
};
//
//Set intial/default values
var set = function(_f, xInterval) {
//context
canvas = document.getElementById("canvas");
canvas.width = window.innerWidth;
if (canvas.getContext) {
context = canvas.getContext('2d'),
width = canvas.width,
height = canvas.height,
//animation
t = 1,
points = [],
//ystart define vertical start to set mirror view
//xstart requiere for xorigin
ystart = 0,
xstart = width/2,
//this y's range is only for this example
y0 = -1,
y1 = 1,
x0 = xInterval[0],
x1 = xInterval[1],
_xscale = ((width) / (x1 - x0)),
_yscale = ((height) / (y1 - y0)),
xorigin = _xscale / 2,
xreal = 0,
yreal =0
f = _f;
}
};
return {
plot: function(fn, xInterval) {
set(fn, xInterval);
eval();
draw();
}
};
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment