<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>canvas 面绘制</title>
<style>
#canvas {
background-color: #f9f9f9;
}
</style>
</head>
<body>
<canvas id="canvas">浏览器不支持 canvas </canvas>
</body>
<script>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
canvas.height = 500;
canvas.width = 500;
// 矩形:红色填充、绿色描边
function drawRect(x, y, width, height) {
ctx.fillStyle = "red";
ctx.strokeStyle = "green";
ctx.fillRect(x, y, width, height);
ctx.strokeRect(x, y, width, height);
}
// 三角形:黄色填充、粉色描边
const points = [
{ x: 300, y: 100 },
{ x: 200, y: 200 },
{ x: 400, y: 200 },
];
function drawTria() {
ctx.fillStyle = "yellow";
ctx.strokeStyle = "pink";
ctx.beginPath();
ctx.moveTo(points[0].x, points[0].y);
ctx.lineTo(points[1].x, points[1].y);
ctx.lineTo(points[2].x, points[2].y);
ctx.closePath();
ctx.fill();
ctx.stroke();
}
// 圆形:绿填充、红色描边
function drawCircle(
x,
y,
radius,
startAngle = 0,
endAngle = Math.PI * 2,
anticlockwise = false
) {
ctx.fillStyle = "green";
ctx.strokeStyle = "red";
ctx.beginPath();
// ctx.arc(圆心-x, 圆心-y, 半径-radius, 开始角度-startAngle, 结束角度-endAngle , anticlockwise 逆时针);
ctx.arc(x, y, radius, startAngle, endAngle, anticlockwise);
ctx.fill();
ctx.stroke();
}
drawRect(50, 50, 100, 50);
drawTria(points);
drawCircle(100, 200, 50);
</script>
</html>
网友评论