user784637
user784637

Reputation: 16122

How to use canvas to change opacity of a context's arc?

I've been able to draw images using a background image source and change the opacity of the background image to 25% like so...

var context = document.getElementById('myCanvas').getContext('2d');
context.globalAlpha=.25;                

var img = new Image();
img.onload = function(){
    context.drawImage(img, 0, 0);             
}                           
img.src = 'pie_crust.png';           

And I've been able to draw single arcs...

var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
var radius = 100;
var startingAngle = 30 * Math.PI/180;
var endingAngle = 60 * Math.PI/180;
var counterclockwise = true;

context.arc(centerX, centerY, radius, startingAngle, endingAngle, counterclockwise);
context.lineWidth = 20;
context.strokeStyle = "black"; // line color
context.stroke(); 

However I haven't been able to change the opacity of a context's arc. For example I have a pie crust (pie_crust.png).

enter image description here

I would like for the user to specify two sets of start and end angles. Let's say the first set is (30, 60) and the second set is (135, 180) and counterclockwise is set to true. I would like those two arcs to have an opacity of 25% and the left over pie crust to have an opacity of 0% so that the resulting canvas would look like this:

enter image description here

How can I use canvas to achieve this effect?

Upvotes: 0

Views: 1201

Answers (1)

kirilloid
kirilloid

Reputation: 14304

You need to just draw image using pie-formed clipping paths, like this:

context.beginPath();
context.arc(centerX, centerY, radius, Math.PI/6, Math.PI/3, true);
context.moveTo(centerX, centerY);
context.closePath();
context.clip();

Upvotes: 2

Related Questions