Pure JavaScript Smooth Gradient Generator

Category: Color , Javascript | September 30, 2016
Author:zsoltc
Views Total:1,878 views
Official Page:Go to website
Last Update:September 30, 2016
License:MIT

Preview:

Pure JavaScript Smooth Gradient Generator

Description:

A pure JavaScript library that allows you to draw smooth gradients on Html5 canvas element.

How to use it:

Load the gradient-generator.dev.js in the document.

<script src="path/to/gradient-generator.dev.js"></script>

Create an Html5 canvas element on where you wish to draw gradients.

<canvas id="canvas" width="500" height="500" style="background: black"></canvas>

The JavaScript to generate gradients using custom colors.

(function () {
  var canvas = document.getElementById('canvas'),
      ctx = canvas.getContext('2d'),
      imageData = ctx.getImageData(0, 0, canvas.getAttribute('width'), canvas.getAttribute('height')),
      pixels = imageData.data,
      gradient = GradientGenerator.createGradient('#000000 #c50106 #f5f100 #ffffff'),
      val,
      color,
      base,
      x,
      y;
  for (y = 0; y < imageData.height; ++y) {
      for (x = 0; x < imageData.width; ++x) {
          val = (x + y) / (imageData.width + imageData.height);
          color = gradient.getColorBytesAt(val);
          base = (y * imageData.width + x) * 4;
          pixels[base] = color.r;
          pixels[base + 1] = color.g;
          pixels[base + 2] = color.b;
          pixels[base + 3] = 255;
      }
  }
  ctx.putImageData(imageData, 0, 0);
})();

Changelog:

09/30/2016

  • Rewritten in ES6

You Might Be Interested In:


Leave a Reply