Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using globalCompositeOperation to create gradient mask

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?

like image 201
hartz89 Avatar asked Feb 27 '26 17:02

hartz89


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.

like image 98
KylePlusPlus Avatar answered Mar 02 '26 06:03

KylePlusPlus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!