万丈高楼平地起,从零开始,使用 canavas 画矩形的多种方式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<style>
#can {
border: 1px solid #999;
}
</style>
<body>
<canvas width="500" height="500" id="can"></canvas>
</body>
<script>
// ctx.beginPath(); 开启一个独立作用域(独立的绘制路径)
// ctx.closePath(); 自动连接起点和终点,形成一个封闭区域
// // 获取画布上下文对象
const ctx = document.getElementById("can").getContext("2d");
//第一种方式:和画直线一样,从0开始,自己手动输入坐标点
// 设置起点坐标
ctx.moveTo(10, 10);
// 设置第一个拐点坐标
ctx.lineTo(310, 10);
// 设置第二个拐点坐标
ctx.lineTo(310, 102);
// 设置第三个拐点坐标
ctx.lineTo(10, 102);
// 设置颜色
ctx.strokeStyle = "skyblue";
// 设置粗细
ctx.lineWidth = "3";
// 自动连接起点和终点,形成一个封闭区域
ctx.closePath();
ctx.stroke();
// 第二种方式:调用内置的矩形方法
ctx.rect(10, 10, 300, 300);
ctx.stroke();
// 第三种方式:调用内置的填充矩形方法
ctx.fillStyle='pink';
ctx.fillRect(10, 10, 300, 300);
ctx.strokeStyle='#999';
ctx.strokeRect(10, 10, 300, 300);
</script>
</html>
今天的分享到此结束,欢迎小伙伴们一起交流