Canvas绘制内角矩形
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>内角矩形</title>
</head>
<body bgcolor="#FFFFFF">
<script type="text/javascript">
var canvas = document.createElement("canvas");
var canW = canH = 600;
canvas.width = canW;
canvas.height = canH;
document.body.appendChild(canvas);
var ctx = canvas.getContext("2d");
var w = 500;
var h = 300;
var x = canW/2 - w/2;
var y = canH/2 - h/2;
var r = 15;
var bdWidth = 2;
var bdColor = "#000000";
var bgcolor = "#FFDAB9";
drawRoundedRect(x,y,w,h,r,bdWidth,bdColor,bgcolor);
function drawRoundedRect(x,y,w,h,r,bdWidth,bdColor,bgcolor){
ctx.beginPath();
ctx.moveTo(x+r,y);
ctx.lineWidth = bdWidth;
ctx.strokeStyle = bdColor;
ctx.fillStyle = bgcolor;
ctx.lineTo(x+w-r,y);
ctx.arcTo(x+w-r,y+r,x+w,y+r,r);
ctx.lineTo(x+w,y+h-r);
ctx.arcTo(x+w-r,y+h-r,x+w-r,y+h,r);
ctx.lineTo(x+r,y+h);
ctx.arcTo(x+r,y+h-r,x,y+h-r,r);
ctx.lineTo(x,y+r);
ctx.arcTo(x+r,y+r,x+r,y,r);
ctx.stroke();
ctx.fill();
ctx.closePath();
}
</script>
</body>
</html>
效果如图:

Canvas绘制外角矩形
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>canvas圆角矩形</title>
</head>
<body>
<canvas id="myCanvas" style="border:1px solid #d3d3d3;">
您的浏览器不支持 HTML5 canvas 标签。</canvas>
<script>
window.onload = function() {
var myCanvas = document.getElementById("myCanvas");
if (myCanvas.getContext("2d")) {
myCanvas.width = 800;
myCanvas.height = 800;
var context = myCanvas.getContext("2d");
strokeRoundRect(context, 10, 10, 600, 300, 10);
} else {
alert("您的浏览器不支持canvas,请换个浏览器试试");
}
};
function strokeRoundRect(cxt, x, y, width, height, radius, lineWidth, strokeColor) {
if (2 * radius > width || 2 * radius > height) { return false; }
cxt.save();
cxt.translate(x, y);
drawRoundRectPath(cxt, width, height, radius);
cxt.lineWidth = lineWidth || 2;
cxt.strokeStyle = strokeColor || "#000";
cxt.stroke();
cxt.restore();
}
function drawRoundRectPath(cxt, width, height, radius) {
cxt.beginPath(0);
cxt.arc(width - radius, height - radius, radius, 0, Math.PI / 2);
cxt.lineTo(radius, height);
cxt.arc(radius, height - radius, radius, Math.PI / 2, Math.PI);
cxt.lineTo(0, radius);
cxt.arc(radius, radius, radius, Math.PI, Math.PI * 3 / 2);
cxt.lineTo(width - radius, 0);
cxt.arc(width - radius, radius, radius, Math.PI * 3 / 2, Math.PI * 2);
cxt.lineTo(width, height - radius);
cxt.closePath();
}
</script>
</body>
</html>
效果如图:
