-2

Hi I am working with the canvas element to create som shapes but I have ran into some problems with the mathematics.

Problem 1: I have to calculate an angle relative to the previous line, I only use 0 to 180 and 0 to -180 degrees.

Problem 1: I have to put a corner radius on the corner how do I draw this on a canvas? Here is an example:

Hope somone can help?

1 Answers1

0

You can use a quadratic curve to make those rounded corners:

enter image description here

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");


roundedRect(20,20,100,75,10);
ctx.stroke();


function roundedRect(x,y,width,height,radius){
    //
    var x1=x+radius;
    var x2=x+width-radius;
    var x3=x+width;
    var y1=y+radius;
    var y2=y+height-radius;
    var y3=y+height;
    //
    ctx.beginPath();
    ctx.moveTo(x1, y);
    ctx.lineTo(x2, y);
    ctx.quadraticCurveTo(x3, y, x3, y1);
    ctx.lineTo(x3, y2);
    ctx.quadraticCurveTo(x3, y3, x2, y3);
    ctx.lineTo(x1, y3);
    ctx.quadraticCurveTo(x, y3, x, y2);
    ctx.lineTo(x, y1);
    ctx.quadraticCurveTo(x, y, x1, y);
    ctx.closePath();
}
body{ background-color: ivory; }
canvas{border:1px solid red;}
<canvas id="canvas" width=300 height=300></canvas>
markE
  • 102,905
  • 11
  • 164
  • 176
  • No need for quadratic curves and lines, just use four arcs - simpler and more efficient. Also, problem 1 (1.) does not seem to be addressed. –  Mar 24 '15 at 02:43
  • Arcs are (by definition) simpler, but quadratic curves are more flexible. Personally, I "grok" qCurves better than arcs for all but the simplest uses -- it resonates with me to define a start + endpoint with the center control point defining the curve. Arcs are a little bit more efficient, but probably not enough to mention except in volume cases. Yeah, question 1.1 is not addressed. :-/ Getting the inbound angle is easy, but I suspect the questioner needs more than this. I was hoping for followup info/question by the OP. BTW, the largest vote-getter on your dup question uses qcurves :-p – markE Mar 24 '15 at 04:15
  • certainly, but it was also answered more than a year before the arc option was shown (which has second place in votes, more than the accepted answer two years before) in any case, point being it was chosen as duplicate as it already answers OPs 2. problem (the first should probably be a question on its own, but can't pick two answers as duplicate and/or unclear question..). Animation is also a volume case btw. Just based on the title of this question I'm not sure we'll much more details on this though.. –  Mar 24 '15 at 05:04