用Canvas绘制出漂亮的花

贝塞尔曲线是一个非常有用的工具,它在很多领域都有应用,特别是在绘图和设计方面。你知道吗,很多带有曲线的形状,像花朵、树叶等,其实都是用贝塞尔曲线绘制出来的。下面这个例子就是用贝塞尔曲线绘制的一朵花,你可以看看它是怎么做的哦。

示例效果与源代码:

运行效果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<!DOCTYPE html>
<html>

<head>
<title>绘制曲线和路径(bezierCurveTo)</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="图形系统开发实战:基础篇 示例">
<meta name="author" content="hjq">
<meta name="keywords" content="canvas,ladder,javascript,图形">
<script src="./js/helper.js"></script>
</head>

<body style="overflow: hidden; margin:10px;">
<canvas id="canvas" width="680" height="240"
style="border:solid 1px #CCCCCC; box-shadow: 4px 4px 8px rgba(0, 0, 0, 0.5);"></canvas>
</body>
<script>
// 从页面中获取画板对象
let canvas = document.getElementById('canvas');
// 从画板中获取“2D渲染上下文”对象
let ctx = canvas.getContext('2d');
// 绘制背景网格线
drawGrid('lightgray', 10, 10);

// 绘制花朵1
drawFlower(ctx, 120, 120, 150, 5, { "color": "red", "fillColor": "green" })

// 绘制花朵2
drawFlower(ctx, 340, 120, 150, 6, { "color": "red", "fillColor": "green" })

// 绘制花朵3
drawFlower(ctx, 560, 120, 150, 7, { "color": "red", "fillColor": "green" })

/**
* 绘制花朵
*/
function drawFlower(ctx, x, y, size, sideNum, style) {
if (sideNum < 3) sideNum = 4;
if (sideNum > 8) sideNum = 6;
size--;
ctx.beginPath();

// 绘制花瓣
for (let n = 0; n < sideNum; n++) {
let theta1 = ((Math.PI * 2) / sideNum) * (n + 1);
let theta2 = ((Math.PI * 2) / sideNum) * (n);
let x1 = (size * Math.sin(theta1)) + x;
let y1 = (size * Math.cos(theta1)) + y;
let x2 = (size * Math.sin(theta2)) + x;
let y2 = (size * Math.cos(theta2)) + y;
ctx.moveTo(x, y);
ctx.bezierCurveTo(x1, y1, x2, y2, x, y);
}
ctx.closePath();
ctx.fillStyle = "red";
ctx.fill();

// 绘制花蕾
ctx.beginPath();
ctx.arc(x, y, size / 5, 0, 2 * Math.PI, false);
ctx.fillStyle = "yellow";
ctx.fill();
ctx.closePath();
}
</script>

</html>

尝试一下 »