block by nitaku 1877405856af3a1c0a37

Canvas gradient

Full Screen

A simple example of HTML5’s canvas element, showing a bilinear color gradient.

index.js

(function() {
  // noprotect;
  var a, b, canvas, ctx, g, height, i, image, r, width, x, y, _i, _j, _ref;

  canvas = d3.select('canvas');

  width = canvas.node().getBoundingClientRect().width;

  height = canvas.node().getBoundingClientRect().height;

  ctx = canvas.node().getContext('2d');

  image = ctx.createImageData(width, height);

  for (x = _i = 0; 0 <= width ? _i < width : _i > width; x = 0 <= width ? ++_i : --_i) {
    for (y = _j = 0; 0 <= height ? _j < height : _j > height; y = 0 <= height ? ++_j : --_j) {
      i = (y * width + x) * 4;
      _ref = [i + 0, i + 1, i + 2, i + 3], r = _ref[0], g = _ref[1], b = _ref[2], a = _ref[3];
      image.data[r] = x / width * 255;
      image.data[g] = 0;
      image.data[b] = y / height * 255;
      image.data[a] = 255;
    }
  }

  ctx.putImageData(image, 0, 0);

}).call(this);

index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="description" content="Canvas gradient" />
    <title>Canvas gradient</title>
    <link rel="stylesheet" href="index.css">
    <script src="//d3js.org/d3.v3.min.js"></script>
</head>
<body>
  <canvas width="960" height="500"></canvas>
  
  <script src="index.js"></script>
</body>
</html>

index.coffee

`// noprotect`

canvas = d3.select('canvas')
width = canvas.node().getBoundingClientRect().width
height = canvas.node().getBoundingClientRect().height

ctx = canvas.node().getContext('2d')
image = ctx.createImageData(width, height)

for x in [0...width]
  for y in [0...height]
    i = (y*width+x)*4
    [r,g,b,a] = [i+0,i+1,i+2,i+3]
    
    image.data[r] = x/width*255
    image.data[g] = 0
    image.data[b] = y/height*255
    image.data[a] = 255
  
ctx.putImageData(image,0,0)