canvas实现长方形梯形
时间: 2023-12-05 22:39:00 浏览: 68
以下是使用canvas实现长方形和梯形的示例代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>Canvas Rectangle and Trapezoid</title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="400" height="400"></canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
// 绘制长方形
ctx.fillStyle = "#FF0000";
ctx.fillRect(50, 50, 100, 75);
// 绘制梯形
ctx.beginPath();
ctx.moveTo(200, 50);
ctx.lineTo(300, 50);
ctx.lineTo(250, 125);
ctx.lineTo(150, 125);
ctx.closePath();
ctx.fillStyle = "#00FF00";
ctx.fill();
</script>
</body>
</html>
```
在上面的代码中,我们使用了canvas的getContext()方法获取了一个2d绘图上下文对象ctx。然后,我们使用fillRect()方法绘制了一个长方形,fillStyle属性设置了填充颜色。接着,我们使用beginPath()方法开始绘制梯形,使用moveTo()方法移动到起始点,使用lineTo()方法绘制线段,最后使用fill()方法填充颜色。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![](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)