HTML <canvas>标签用于绘制图形。它指定了网页的一个部分,可以使用脚本制作各种对象、图形、动画和照片合成。
这是 HTML5 中包含的一个新标签。<canvas>标签只是视觉对象的容器,因此,如果要绘制它们,则应使用脚本。在使用 <canvas> 标签 时,区分经常混淆的想法(如 <canvas> 标签)和元素的上下文至关重要。画布上下文是一个对象,具有自己的一组属性和呈现策略。上下文可以是 2D 或 3D。<canvas> 标签只能有一个上下文。
语法
<canvas> ... </canvas>
属性
<canvas> 标签支持 HTML 的 全局属性 和 事件属性。也接受一些特定属性,这些属性在下面列出。
属性 | 值 | 描述 |
---|---|---|
height | pixels | 指定创建的画布的高度,默认值为 150。 |
width | pixels | 指定已创建画布的宽度,默认值为 300。 |
<canvas> 标签示例
下面的示例将说明 <canvas> 标签的用法。在哪里、何时以及如何使用它来使用 <canvas> 标签创建图形,以及我们如何使用 CSS 设置该图形的样式。
使用 Canvas 标签创建图形
让我们看一下以下示例,我们将使用 <canvas> 标签绘制圆圈。
<!DOCTYPE html>
<html>
<body>
<canvas id = "QikepuCom" height = "200" width = "210" style = "border:2px solid #8E44AD ">
</canvas>
<script>
var x = document.getElementById("QikepuCom");
var y = x.getContext("2d");
y.beginPath();
y.arc(100, 100, 90, 0, 2 * Math.PI);
y.stroke();
</script>
</body>
</html>
创建文本图形
考虑以下示例,我们将使用 <canvas> 标签和 strokeText() 方法在画布上绘制文本。
<!DOCTYPE html>
<html>
<body>
<canvas id="QikepuCom" width="1000" height="100"></canvas>
<script>
var x = document.getElementById("QikepuCom");
var y = x.getContext("2d");
y.font = "60px verdana";
y.strokeStyle = "green";
y.strokeText("QikepuCom", 20, 60);
</script>
</body>
</html>
<canvas> 标签的图形css样式
以下示例,我们将用<canvas> 标签制作线性渐变并用渐变填充矩形。
<!DOCTYPE html>
<html>
<body>
<canvas id="Qikepu" width="600" height="150" style="border:2px solid #D2B4DE;"></canvas>
<script>
var x = document.getElementById("Qikepu");
if (x.getContext) {
var y = x.getContext("2d");
var gradient = y.createLinearGradient(11, 91, 210, 89);
gradient.addColorStop(0, '#DE3163');
gradient.addColorStop(1, '#D5F5E3 ');
y.fillStyle = gradient;
y.fillRect(11, 12, 570, 120);
}
</script>
</body>
</html>
嵌套图形
在以下示例中,我们将使用 fillText() 方法在画布上绘制文本。
<!DOCTYPE html>
<html>
<body>
<canvas id="Qikepu" width="500" height="200" style="border:3px solid #27AE60"></canvas>
<script>
var x = document.getElementById("Qikepu");
var y = x.getContext("2d");
y.font = "bold 35px solid";
y.fillText("QikepuCom", 100, 100);
</script>
</body>
</html>
支持的浏览器
浏览器 | ![]() |
![]() |
![]() |
![]() |
![]() |
---|---|---|---|---|---|
<canvas> | 4.0 | 9.0 | 2.0 | 3.1 | 9.0 |