效果圖:
完整代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
#cvs {
background-color: #ccc;
}
</style>
</head>
<body>
<div id='container'>
<canvas id='cvs'>
sorry, your browser doesn't support canvas API.
</canvas>
</div>
</body>
<script>
window.onload = function() {
// 獲取畫布
const cvs = document.querySelector('#cvs')
cvs.width = 800
cvs.height = 800
// 獲取畫筆
const ctx = cvs.getContext('2d')
// 循環化矩形,黑白各20次
for(let i = 0; i < 20; i++) {
// 從最外層往內部逐個畫矩形,最外層黑色矩形起點座標爲(200, 100),寬度爲 400,最外層白色矩形起點座標爲(205,105),寬度爲 390。因爲線寬是 5,每畫一個矩形,第二個矩形的橫縱座標偏移 10,寬度減少 10 * 2
drawRect(ctx, 200 + i * 10, 100 + i * 10, 400 - i * 10 * 2, 400 - i * 10 * 2, 5, '#000')
drawRect(ctx, 205 + i * 10, 105 + i * 10, 390 - i * 10 * 2, 390 - i * 10 * 2, 5, '#fff')
}
}
// 封裝繪製矩形的函數,傳入參數依次爲 畫筆,矩形橫座標,矩形縱座標,矩形寬度,矩形高度,矩形線寬,矩形顏色
function drawRect(ctx, x, y, width, height, lineWidth = 1, strokeStyle = '#000') {
// 繪製矩形,兩種方式
ctx.beginPath()
// 方式一
// ctx.moveTo(x, y)
// ctx.lineTo(x + width, y)
// ctx.lineTo(x + width, y + height)
// ctx.lineTo(x, y + height)
// ctx.lineTo(x, y)
// ctx.closePath()
// 方式二
ctx.rect(x, y, width, height)
// 設置線寬和顏色
ctx.lineWidth = lineWidth
ctx.strokeStyle = strokeStyle
// 繪製
ctx.stroke()
}
</script>
</html>