HTML Canvas - 第一个应用程序


在前面的章节中,我们已经了解了如何使用 <canvas> 标签创建 Canvas 元素。现在我们将使用简单的 CSS 样式来设置 Canvas 元素的样式,这有助于我们了解 Canvas 元素是如何形成的。

让我们首先使用以下属性创建一个空的 Canvas 元素和样式

  • 添加背景颜色

  • 更改边框

向 Canvas 元素添加背景颜色

以下代码演示了如何使用 CSS 样式属性向 Canvas 元素添加颜色。我们使用Canvas 元素的background_color属性。代码如下。

<!DOCTYPE html> <html lang="en"> <head> <title>Canvas Element</title> <style> #canvas{ border:5px solid black; background-color: green; } </style> </head> <body> <canvas id="canvas" width="300" height="150" > This text is displayed if your browser does not support HTML5 Canvas or if JavaScript is disabled. </canvas> </body> </html>

输出

以下代码给出的输出为

添加背景颜色

更改 Canvas 元素的边框

通过使用CSS样式属性,我们可以轻松地改变Canvas元素的边框样式。使用 Canvas 创建交互式视觉图形时它非常有用。以下是更改Canvas元素边框样式的实现。

<!DOCTYPE html> <html lang="en"> <head> <title>Canvas Element</title> <style> #canvas{ border:2px dotted black; } </style> </head> <body> <canvas id="canvas" width="300" height="150" > This text is displayed if your browser does not support HTML5 Canvas or if JavaScript is disabled. </canvas> </body> </html>

输出

在创建 Canvas 元素时,我们可以使用以下方法之一来根据我们的要求更改 Canvas 边框的样式,而不是使用实体

  • 点状

  • 虚线

  • 双倍的

上述代码的输出是

改变边界