Skip to content

Instantly share code, notes, and snippets.

@AMStrix
Last active December 7, 2017 04:58
Show Gist options
  • Save AMStrix/14f4a4b1c0b268708376b5412ece1526 to your computer and use it in GitHub Desktop.
Save AMStrix/14f4a4b1c0b268708376b5412ece1526 to your computer and use it in GitHub Desktop.
Simple function graph implemented in JS/HTML
<!DOCTYPE html>
<html>
<head>
<title>Canvas code example</title>
<script type="text/javascript">
// http://www.javascripter.net/faq/plotafunctiongraph.htm
function fun1(x) {return Math.sin(x); }
function fun2(x) {return Math.cos(3*x);}
function draw() {
var canvas = document.getElementById("canvas");
if (null==canvas || !canvas.getContext) return;
var axes={}, ctx=canvas.getContext("2d");
axes.x0 = .5 + .5*canvas.width; // x0 pixels from left to x=0
axes.y0 = .5 + .5*canvas.height; // y0 pixels from top to y=0
axes.scale = 40; // 40 pixels from x=0 to x=1
axes.doNegativeX = true;
showAxes(ctx,axes);
funGraph(ctx,axes,fun1, fun2,"rgb(11,153,11)",1);
//funGraph(ctx,axes,fun2,"rgb(66,44,255)",2);
}
function funGraph (ctx, axes, funcX, funcY, color, thick) {
var tt, xx, yy, dt=4, x0=axes.x0, y0=axes.y0, scale=axes.scale;
var iMax = Math.round((ctx.canvas.width-x0)/dt);
var iMin = axes.doNegativeX ? Math.round(-x0/dt) : 0;
ctx.beginPath();
ctx.lineWidth = thick;
ctx.strokeStyle = color;
for (var i=iMin;i<=iMax;i++) {
tt = dt*i;
xx = scale*funcX(tt/scale);
yy = scale*funcY(tt/scale);
if (i==iMin) ctx.moveTo(x0+xx,y0-yy);
else ctx.lineTo(x0+xx,y0-yy);
}
ctx.stroke();
}
function showAxes(ctx,axes) {
var x0=axes.x0, w=ctx.canvas.width;
var y0=axes.y0, h=ctx.canvas.height;
var xmin = axes.doNegativeX ? 0 : x0;
ctx.beginPath();
ctx.strokeStyle = "rgb(128,128,128)";
ctx.moveTo(xmin,y0); ctx.lineTo(w,y0); // X axis
ctx.moveTo(x0,0); ctx.lineTo(x0,h); // Y axis
ctx.stroke();
}
</script>
</head>
<body onload="draw()">
<canvas id="canvas" width="502" height="108"></canvas>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment