1

I want to draw two objects on the canvas with an opacity of 0.2.

Both items partly overlap. Where they overlap, the opacity will be 0.4, as compared to 0.2 for the non-overlapping parts. i.e. canvas 100w, 100h.

https://jsbin.com/wicigarinu/edit?js,output

ctx.globalAlpha = 0.2;
ctx.beginPath();
ctx.arc(50, 50, 25, 0, 2*Math.PI, false);
ctx.fill();
ctx.closePath();

ctx.beginPath();
ctx.arc(65, 65, 20, 0, 2*Math.PI, false);
ctx.fill();
ctx.closePath();

How would i be able to draw on the same spot, but keep the originally set opacity, even on coordinates where more than 1 fill happens ?

user431806
  • 396
  • 5
  • 17
  • There's no "native" way to do that wit the canvas. Maybe some frameworks would implement that, but that need to be googled. Without third-party libs you'll need to draw compound figures in such a way that there are no overlapping regions. – Eduard Malakhov Jan 28 '17 at 17:24
  • http://stackoverflow.com/a/17623263/1693593 –  Jan 29 '17 at 22:20

1 Answers1

2

You can draw on a helper canvas with full opacity, then copy to the real canvas with alpha < 1.

Here's a basic example for this:

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

//create helper canvas
const hCanvas = document.createElement('canvas');
const hCtx = hCanvas.getContext('2d');

//draw on helper canvas
hCtx.beginPath();
hCtx.arc(50, 50, 25, 0, 2*Math.PI, false);
hCtx.fill();
hCtx.closePath();

hCtx.beginPath();
hCtx.arc(65, 65, 20, 0, 2*Math.PI, false);
hCtx.fill();
hCtx.closePath();

//copy to real canvas with alpha < 1
ctx.globalAlpha = 0.2;
ctx.drawImage(hCanvas, 0, 0);
<canvas id="canvas"></canvas>
Giladd
  • 1,351
  • 8
  • 9