Languages
[Edit]
EN

JavaScript - draw function chart on canvas element

10 points
Created by:
Elmer-Li
336

In this short article, we would like to show a simple way how to plot a chart on HTML5 canvas element using JavaScript.

Math.sin(), Math.cos() and x^2 plot on HTMl5 canvas element using JavaScript.
Math.sin(), Math.cos() and x^2 plot 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>y = Math.sin(x)</div>
  <canvas id="sin-canvas" width="400" height="130"></canvas>
  
  <div>y = Math.cos(x)</div>
  <canvas id="cos-canvas" width="400" height="130"></canvas>
  
  <div>y = x^2</div>
  <canvas id="x2-canvas" width="400" height="250"></canvas>
  
  <script>
    
    function Calculator(canvas, x1, x2, y1, y2, func) {
      	var self = this;

      	var width = canvas.width;
      	var height = canvas.height;

      	var xRange = x2 - x1;
      	var yRange = y2 - y1;

        self.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 * width,
                y: ny * height
            };
        };
    }
    
    function Chart(canvas, x1, x2, y1, y2, dx, func) {
      	var self = this;
    	
      	var context = canvas.getContext('2d');
      	var calculator = new Calculator(canvas, x1, x2, y1, y2, func);
      
      	self.drawChart = function(color, width) {
        	context.beginPath();
          
            var point = calculator.calculatePoint(x1);
            context.moveTo(point.x, point.y);

            for (var x = x1 + dx; x < x2; x += dx) {
                var point = calculator.calculatePoint(x);
                context.lineTo(point.x, point.y);
            }
          
            var point = calculator.calculatePoint(x2);
            context.lineTo(point.x, point.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>

See also

  1. JavaScript - draw derivative on canvas element

  2. JavaScript - draw integral on canvas element

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join