HTML5 Canvas笔记——Canvas绘制矩形(外角矩形和
2020-04-26 本文已影响0人
没昔
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; //开始的x轴坐标
var y = canH/2 - h/2; //开始的y轴坐标
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")) {
//设置canvas的宽度和高度
myCanvas.width = 800;
myCanvas.height = 800;
var context = myCanvas.getContext("2d");
//绘制一个圆角矩形
strokeRoundRect(context, 10, 10, 600, 300, 10);
} else {
alert("您的浏览器不支持canvas,请换个浏览器试试");
}
};
/**该方法用来绘制圆角矩形
*@param cxt:canvas的上下文环境
*@param x:左上角x轴坐标
*@param y:左上角y轴坐标
*@param width:矩形的宽度
*@param height:矩形的高度
*@param radius:圆的半径
*@param lineWidth:线条粗细
*@param strokeColor:线条颜色
**/
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; //若是给定了值就用给定的值否则给予默认值2
cxt.strokeStyle = strokeColor || "#000";
cxt.stroke();
cxt.restore();
}
function drawRoundRectPath(cxt, width, height, radius) {
cxt.beginPath(0);
//从右下角顺时针绘制,弧度从0到1/2PI
cxt.arc(width - radius, height - radius, radius, 0, Math.PI / 2);
//矩形下边线
cxt.lineTo(radius, height);
//左下角圆弧,弧度从1/2PI到PI
cxt.arc(radius, height - radius, radius, Math.PI / 2, Math.PI);
//矩形左边线
cxt.lineTo(0, radius);
//左上角圆弧,弧度从PI到3/2PI
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>