EN
JavaScript - draw function chart on canvas element
10
points
In this short article, we would like to show a simple way how to plot a chart on HTML5 canvas element using JavaScript.
Practical example:
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<style> canvas { border: 1px solid silver; } </style>
</head>
<body>
<div><div>y = Math.sin(x)</div><canvas id="sin-canvas" width="400" height="130"></canvas></div>
<div><div>y = Math.cos(x)</div><canvas id="cos-canvas" width="400" height="130"></canvas></div>
<div><div>y = x^2 </div><canvas id="x2-canvas" width="400" height="250"></canvas></div>
<script>
function Calculator(canvas, x1, x2, y1, y2, func) {
var cWidth = canvas.width;
var cHeight = canvas.height;
var xRange = x2 - x1;
var yRange = y2 - y1;
this.calculatePoint = function(x) {
var y = func(x);
// chart will be reversed horizontaly because of reversed canvas pixels
var nx = (x - x1) / xRange; // normalized x
var ny = 1.0 - (y - y1) / yRange; // normalized y
return {
x: nx * cWidth,
y: ny * cHeight
};
};
}
function Chart(canvas, x1, x2, y1, y2, dx, func) {
var context = canvas.getContext('2d');
var calculator = new Calculator(canvas, x1, x2, y1, y2, func);
this.drawChart = function(color, width) {
var a = calculator.calculatePoint(x1);
var b = calculator.calculatePoint(x2);
context.beginPath();
context.moveTo(a.x, a.y);
for (var x = x1 + dx; x < x2; x += dx) {
var point = calculator.calculatePoint(x);
context.lineTo(point.x, point.y);
}
context.lineTo(b.x, b.y);
context.strokeStyle = color || 'black';
context.lineWidth = width || 1;
context.stroke();
};
}
// Usage example:
var sinCanvas = document.querySelector('#sin-canvas');
var cosCanvas = document.querySelector('#cos-canvas');
var x2Canvas = document.querySelector('#x2-canvas');
var dx = 0.1; // x value step
var sinChart = new Chart(sinCanvas, 0, 2 * Math.PI, -1, +1, dx, Math.sin); // x: <0, 360> degress
var cosChart = new Chart(cosCanvas, 0, 2 * Math.PI, -1, +1, dx, Math.cos); // x: <0, 360> degress
var x2Chart = new Chart(x2Canvas, -2, +2, 0, 4, dx, function(x) { return x * x });
sinChart.drawChart('red', 1);
cosChart.drawChart('blue', 2);
x2Chart.drawChart('orange', 3);
</script>
</body>
</html>