我的页面背景中是否可以使用 HTML canvas 元素?
在本文中,我们将学习如何在页面背景中使用 HTML canvas 元素。
您可以尝试添加一个 CSS 样式,使用 position: fixed(或根据需要使用 absolute),以便之后出现的任何内容都位于其顶部。
为了更好地理解如何在页面背景中使用 HTML canvas 元素,让我们来看一下下面的示例……
示例 1
在下面的示例中,我们使用 position: absolute 来应用 CSS 样式到 canvas。
<!DOCTYPE html>
<html>
<style>
canvas{
position:absolute;
left:0;
top:0;
z-index:-1;
}
div{
position:absolute;
z-index:0;
left:11px;
top:14px;
}
</style>
<body>
<canvas id="mytutorial" width="450" height="500" style="border:1px solid #ABEBC6;"></canvas>
<div>Welcome To Tutorialspoint</div>
<script>
var c = document.getElementById("mytutorial");
var ctx = c.getContext("2d");
var grd = ctx.createLinearGradient(0, 0, 600, 600);
grd.addColorStop(0, "#D35400");
grd.addColorStop(1, "#73C6B6");
ctx.fillStyle = grd;
ctx.fillRect(0, 0, 600, 600)
</script>
</body>
</html>
运行上述脚本后,输出窗口会弹出,显示 canvas 作为背景,网页上显示文本“欢迎来到 tutorialspoint”。
示例 2
让我们考虑另一个在页面背景中使用 HTML canvas 元素的示例。
<!DOCTYPE html>
<html>
<style>
body {
background: #dddddd;
}
#tutorial {
margin: 20px;
padding: 20px;
background: #ffffff;
border: thin inset #aaaaaa;
width: 600px;
height: 300px;
}
</style>
<body>
<canvas id='tutorial'></canvas>
<script>
var canvas = document.getElementById('tutorial'),
context = canvas.getContext('2d');
context.font = '38pt arial';
context.strokeStyle = '#82E0AA';
context.strokeText('Welcome', canvas.width/2 - 150, canvas.height/2 + 15 );
</script>
</body>
</html>
运行上述脚本后,它将生成一个输出,其中包含在 canvas 上填充的描边文本,显示在网页上,充当页面的背景。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP