HTML Canvas 基础知识
htmlweb developmentfront end technology更新于 2025/11/21 15:40:17
要在网页上绘制画布,请使用 HTML5 Canvas 元素。<canvas> 元素允许您使用 JavaScript 绘制图形。使用 Canvas,您可以绘制直线、矩形、贝塞尔曲线等。
每个 Canvas 都有两个元素,分别描述其高度和宽度,即 height 和 width。
此外,您还需要为 Canvas 设置一个 ID,如以下代码片段所示 −
<canvas id = "newCanvas" width = "100" height = "100"></canvas>
找到 <canvas>使用 getElementById() 方法来获取 DOM 元素。 −
var canvas = document.getElementById("newCanvas");
要在画布上显示内容,脚本首先需要访问渲染上下文并在其上进行绘制。<canvas> 有一个名为 getContext 的 DOM 方法,用于获取渲染上下文及其绘制函数。此函数接受一个参数,即 context2d 的类型。
现在让我们看一个在 HTML5 中使用 <canvas> 绘制路径的示例 −
示例
<!DOCTYPE HTML>
<html>
<head>
<style>
#test {
width: 100px;
height:100px;
margin: 0px auto;
background-color: orange;
}
</style>
<script>
function drawShape() {
// get the canvas element using the DOM
var canvas = document.getElementById('mycanvas');
// Make sure we don't execute when canvas isn't supported
if (canvas.getContext) {
// use getContext to use the canvas for drawing
var ctx = canvas.getContext('2d');
// Draw shapes
ctx.beginPath();
ctx.arc(75,75,50,0,Math.PI*2,true); // Outer circle
ctx.moveTo(110,75);
ctx.arc(75,75,35,0,Math.PI,false); // Mouth
ctx.moveTo(65,65);
ctx.arc(60,65,5,0,Math.PI*2,true); // Left eye
ctx.moveTo(95,65);
ctx.arc(90,65,5,0,Math.PI*2,true); // Right eye
ctx.stroke();
} else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
}
}
</script>
</head>
<body id = "test" onload = "drawShape();">
<canvas id = "mycanvas"></canvas>
</body>
</html>
输出
这将产生以下输出 −

让我们看另一个在 HTML5 中绘制二次曲线的示例 −
示例
<!DOCTYPE HTML>
<html>
<head>
<style>
#test {
width: 100px;
height:100px;
margin: 0px auto;
}
</style>
<script type>
function drawShape() {
// 使用 DOM 获取 Canvas 元素
var canvas = document.getElementById('mycanvas');
// 确保在 Canvas 不受支持时不会执行此操作
if (canvas.getContext) {
// 使用 getContext 来使用 Canvas 进行绘图
var ctx = canvas.getContext('2d');
// 绘制形状
ctx.beginPath();
ctx.moveTo(75,25);
ctx.quadraticCurveTo(25,25,25,62.5);
ctx.quadraticCurveTo(25,100,50,100);
ctx.quadraticCurveTo(50,120,30,125);
ctx.quadraticCurveTo(60,120,65,100);
ctx.quadraticCurveTo(125,100,125,62.5);
ctx.quadraticCurveTo(125,25,75,25);
ctx.stroke();
} else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
}
}
</script>
</head>
<body id = "test" onload = "drawShape();">
<canvas id = "mycanvas"></canvas>
</body>
</html>
输出
这将产生以下输出 −

相关文章
有用资源
html 参考教程 - 该教程包含有关 html 的更多信息:https://www.cainiaomax.com/html/

