Appearance
html
<!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>
<style>
html,
body {
width: 100vw;
height: 100vh;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
const canvas = document.querySelector('#canvas')
const context = canvas.getContext('2d')
canvas.style.background = '#ddd'
const roundedRect = (x, y, width, height, borderRadius) => {
context.moveTo(width > 0 ? x + borderRadius : x - borderRadius, y)
// 不使用 beginPath,正好省略绘制直线的操作。
// top
context.arcTo(x + width, y, x + width, y + height, borderRadius)
// right
context.arcTo(x + width, y + height, x, y + height, borderRadius)
// bottom
context.arcTo(x, y + height, x, y, borderRadius)
// left
// 上一个子路径连接到新子路径的的起点,
// 新子路径的起点不是 (x, y),而是绘制出来的圆弧的起点。
context.arcTo(x, y, width > 0 ? x + borderRadius : x - borderRadius, y, borderRadius)
}
const drawRoundedRect = (x, y, width, height, borderRadius, strokeColor = 'black', fillColor = 'transparent') => {
context.beginPath()
roundedRect(x, y, width, height, borderRadius)
context.strokeStyle = strokeColor
context.fillStyle = fillColor
context.stroke()
context.fill()
}
drawRoundedRect(10, 10, 50, 50, 10, 'red')
drawRoundedRect(120, 10, -50, 50, 15, 'green')
drawRoundedRect(130, 60, 50, -50, 20, 'blue')
drawRoundedRect(240, 60, -50, -50, 25, 'red')
</script>
</body>
</html>