John Reid
John Reid

Reputation: 1185

How to get box dimensions of canvas context?

I'm just getting into using the canvas element in HTML.

I've hit a snag where I am overlaying an image with paths. When someone clicks on the path, I can use the isPointInPath method to know which path has been clicked on.

The problem is that I want to redraw the image zoomed into the outer border of the path but I can't see a way to retrieve that information.

ctx.beginPath();
ctx.arc(can.width / 2, can.height / 2, can.height / 2.5, ((2 * Math.PI) / 10) * 7, (2 * Math.PI) / 10);
ctx.lineTo(can.width / 2, can.height / 2);
ctx.closePath();

In this fiddle http://jsfiddle.net/JohnSReid/78PEX/, I've drawn an arc. If I use the points that I've drawn like in the code above then I'll crop the outer points of the arc.

Is there a way to grab full the dimensions of the area that the arc is using?

Upvotes: 0

Views: 567

Answers (1)

markE
markE

Reputation: 105015

Demo: http://jsfiddle.net/m1erickson/9xgwY/

enter image description here

You can get any point on the circumference of a circle (or your arc) like this:

function XYonCircle(cx,cy,radius,radians){
    var x=cx+radius*Math.cos(radians);
    var y=cy+radius*Math.sin(radians);
    return({x:x,y:y});
}

To get the bounding-box of your arc:

var cw=canvas.width;
var ch=canvas.height;
var PI2=Math.PI*2;

var left=XYonCircle(cw/2,ch/2,ch/2.5,PI2/10*7).x;
var top=XYonCircle(cw/2,ch/2,ch/2.5,PI2*.75).y;
var right=XYonCircle(cw/2,ch/2,ch/2.5,0).x;
var bottom=XYonCircle(cw/2,ch/2,ch/2.5,PI2/10).y;

If you change your arc, some bounding points will be at any of these angles that the arc passes through: 0,PI/2,PI & PI*3/2.

The remaining bounding points will be at the starting and ending of the arc.

Upvotes: 3

Related Questions