Domanda

I am trying to create an overlay that can highlight certain portions of the page. The best way I've figured out to do this is to use a canvas fit to the page, draw the shapes I need, and draw a rectangle using this trick:

ctx.rect(canvas.width, 0, 0 - canvas.width, canvas.height);

I'm not sure I can explain this well, so it might be best to look at the jsFiddle example here to get an idea of what I am trying to do.

This works perfectly in every browser except Safari. Is there any way to achieve this effect in Safari?

È stato utile?

Soluzione

You can try filling the whole canvas first, then use composite mode to knock out the shapes.

Example:

ctx.fillStyle = "rgba(0, 0, 0, 0.5)";
ctx.fillRect(canvas.width, 0, 0 - canvas.width, canvas.height);

// next shape will punch hole in the draw rectangle above
ctx.globalCompositeOperation = 'destination-out';
ctx.fillStyle = "rgba(0, 0, 0, 1)";  // make sure alpha is 100%

ctx.beginPath();
ctx.moveTo(300, 60);
ctx.arc(300, 60, 50, 0, 2 * Math.PI);
ctx.moveTo(500, 160);
ctx.arc(500, 160, 50, 0, 2 * Math.PI);
drawEllipse(ctx, 103, 23, 100, 30)
drawEllipse(ctx, 503, 23, 100, 30)
ctx.fill();

ctx.globalCompositeOperation = 'source-over';  // reset comp. mode

Modifed fiddle here

Alpha (not the color) will determine how much visible the hole will be.

Hope this helps.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top