
<!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 = 400;
myCanvas.height = 200;
var context = myCanvas.getContext("2d");
strokeRoundRect(context, 10, 10, 100, 50, 10);
fillRoundRect(context, 200, 10, 100, 50, 10, 'rgba(0,0,0,0.7)');
} else {
alert("您的浏览器不支持canvas,请换个浏览器试试");
}
};
function fillRoundRect(cxt, x, y, width, height, radius, fillColor) {
if (2 * radius > width || 2 * radius > height) { return false; }
cxt.save();
cxt.translate(x, y);
drawRoundRectPath(cxt, width, height, radius);
cxt.fillStyle = fillColor || "#000";
cxt.fill();
cxt.restore();
}
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>