Using globalCompositeOperation to create gradient mask

Viewed 145

I am trying to use canvas's globalCompositeOperation='destination-in' setting to draw a series of dots that are masked by a radial gradient. My desired outcome is shown in the screenshot below:

desired outcome

Instead, my canvas is showing the solid gradient with none of the dots visible. Here's my JS:

var canvas = document.getElementById('canvas')
  , ctx = canvas.getContext('2d');

var coordMatrix = [
  [50, 100, 150, 50, 100, 150],
  [50,  50, 50, 100, 100, 100]
];

var gradient = ctx.createRadialGradient(100, 100, 0, 100, 100, 100);
gradient.addColorStop(0, 'red');
gradient.addColorStop(1, 'blue');
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, 200, 200);

ctx.globalCompositeOperation = 'destination-in';

coordMatrix[0].forEach(function(xCoord, i) {
  var yCoord = coordMatrix[1][i];
  ctx.moveTo(xCoord, yCoord);
  ctx.arc(xCoord, yCoord, 10, 0, Math.PI * 2, false);
});

And here's a fiddle:

https://jsfiddle.net/73d9jawn/2/

Am I missing something?

1 Answers

You forgot to call ctx.fill() after setting the coordinates for the arcs. Also, you need to call ctx.fill() after the forEach has completed all iterations, otherwise globalCompositeOperation only applies to the first circle drawn. Here is an updated fiddle.

Related