用canvas写一个圣诞树
时间: 2023-11-18 21:02:14 浏览: 28
您好!下面是用 HTML5 Canvas 绘制圣诞树的代码示例:
```
<!DOCTYPE html>
<html>
<head>
<style>
canvas {
border: 1px solid #d3d3d3;
background-color: #f1f1f1;
}
</style>
</head>
<body onload="start()">
<canvas id="myCanvas" width="300" height="150"></canvas>
<script>
function start() {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
// 绘制圣诞树
ctx.beginPath();
ctx.moveTo(150, 0);
ctx.lineTo(225, 150);
ctx.lineTo(75, 150);
ctx.lineTo(150, 0);
ctx.closePath();
// 填充圣诞树
ctx.fillStyle = "green";
ctx.fill();
// 绘制圣诞树的树干
ctx.moveTo(150, 150);
ctx.lineTo(150, 300);
ctx.stroke();
// 绘制圣诞树的装饰品
ctx.beginPath();
ctx.arc(100, 100, 25, 0, 2 * Math.PI);
ctx.fillStyle = "red";
ctx.fill();
ctx.beginPath();
ctx.arc(200, 100, 25, 0, 2 * Math.PI);
ctx.fillStyle = "yellow";
ctx.fill();
ctx.beginPath();
ctx.arc(150, 75, 25, 0, 2 * Math.PI);
ctx.fillStyle = "blue";
ctx.fill();
}
</script>
</body>
</html>
```
希望这个示例能帮到您!
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)