1. 使用Canvas绘制(1)矩形、(2)三角形、(3)扇形、(4)文本、(5)图像、(6)视频。
时间: 2024-06-09 08:04:26 浏览: 147
以下是使用Canvas绘制的示例代码:
1. 绘制矩形:
```html
<canvas id="myCanvas" width="200" height="100"></canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "#FF0000";
ctx.fillRect(0, 0, 150, 75);
</script>
```
2. 绘制三角形:
```html
<canvas id="myCanvas" width="200" height="100"></canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.moveTo(100, 20);
ctx.lineTo(20, 80);
ctx.lineTo(180, 80);
ctx.closePath();
ctx.stroke();
</script>
```
3. 绘制扇形:
```html
<canvas id="myCanvas" width="200" height="100"></canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.moveTo(100, 50);
ctx.arc(100, 50, 40, 0, Math.PI/2, false);
ctx.closePath();
ctx.fillStyle = "#FF0000";
ctx.fill();
</script>
```
4. 绘制文本:
```html
<canvas id="myCanvas" width="200" height="100"></canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.font = "30px Arial";
ctx.fillText("Hello World", 10, 50);
</script>
```
5. 绘制图像:
```html
<canvas id="myCanvas" width="200" height="100"></canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var img = new Image();
img.src = "https://www.w3schools.com/tags/img_girl.jpg";
img.onload = function() {
ctx.drawImage(img, 0, 0);
};
</script>
```
6. 播放视频:
```html
<canvas id="myCanvas" width="640" height="360"></canvas>
<video id="myVideo" width="640" height="360" controls>
<source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var video = document.getElementById("myVideo");
video.addEventListener('play', function() {
var $this = this;
(function loop() {
if(!$this.paused && !$this.ended) {
ctx.drawImage($this, 0, 0);
setTimeout(loop, 1000 / 30);
}
})();
}, 0);
</script>
```
以上是使用Canvas绘制矩形、三角形、扇形、文本、图像、视频的示例代码。
阅读全文