Languages
[Edit]
EN

JavaScript - draw Rastrigin 2D on canvas element

10 points
Created by:
Reilly-Collier
410

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

Rastrigin 2D chart on HTML5 canvas element using JavaScript.
Rastrigin 2D chart on HTML5 canvas element using JavaScript.

Used formula:

// ONLINE-RUNNER:browser;

const rastrigin2D = function(x) {
    return 10 + x * x - 10 * Math.cos(2 * Math.PI * x);
};


// Usage example:

console.log(rastrigin2D(0));

Practical example: 

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <style> canvas { border: 1px solid silver; } </style>
</head>
<body>
  <div>y = 10 - x² - 10cos(2πx)</div>
  <canvas id="canvas" width="400" height="300"></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 canvas = document.querySelector('#canvas');

    var dx = 0.02;  // x value step
    
    var rastrigin2D = function(x) {
    	return 10 + x * x - 10 * Math.cos(2 * Math.PI * x);
    };

    var chart = new Chart(canvas, -5.12, +5.12, -5, 45, dx, rastrigin2D);

    chart.drawChart('orange', 2);

  </script>
</body>
</html>

References

  1. Rastrigin function - Wikipedia
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