We would like to know how to draw rounded rectangle with bezier Curve.
<!-- w w w. j a v a 2 s . co m-->
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
window.onload=function(){
var K = 4 * (Math.SQRT2-1) / 3; //constant for circles using Bezier curve.
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
canvas.width = 400;
canvas.height = 200;
document.body.appendChild(canvas);
rounded_rect(ctx,10,10,200,150,20);
function rounded_rect(ctx,left,top, width, height, radius)
{
var right=left+width;
var bottom=top+height;
ctx.beginPath();
// top left
ctx.moveTo(left+radius,top);
// top right
ctx.lineTo(right-radius,top);
//right top
ctx.bezierCurveTo(right+radius*(K-1),top,right,top+radius*(1-K),right,top+radius);
//right bottom
ctx.lineTo(right,bottom-radius);
//bottom right
ctx.bezierCurveTo(right,bottom+radius*(K-1),right+radius*(K-1),bottom,right-radius,bottom);
//bottom left
ctx.lineTo(left+radius,bottom);
//left bottom
ctx.bezierCurveTo(left+radius*(1-K),bottom,left,bottom+radius*(K-1),left,bottom-radius);
//left top
ctx.lineTo(left,top+radius);
//top left again
ctx.bezierCurveTo(left,top+radius*(1-K),left+radius*(1-K),top,left+radius,top);
ctx.lineWidth=10;
ctx.strokeStyle="rgb(0,0,0)";
ctx.stroke();
}
}
</script>
</head>
<body>
</body>
</html>
The code above is rendered as follows: