前言
Canvas(画布)是在HTML5中新增的标签用于在网页实时生成图像,它可以说是html中最复杂的一个标签,为什么呢?因为它的属性和方法太多了。接下来我们就来用这个标签来实现古人诗句中的满天星,看下图:
用法
Canvas(画布)标签的具体说明详见HTML CanvasHTML5 Canvas (w3school.com.cn),在这我截了两张图有一些属性和方法:
我们先来实现画一个红色矩形出来,先创建一个html,在body标签里面放上canvas标签
<canvas id="canvas"></canvas>
利用css设置这个标签的样式
<style>
#canvas {
border: 1px solid #000;
}
</style>
再利用js生成图画
<script>
//拿到canvas
let canvas = document.getElementById("canvas");
//创建二维的画布
let ctx = canvas.getContext("2d");
//从坐标(10,10)开始,画一个长100,宽100的矩形
ctx.rect(10, 10, 100, 100)
//设置填充背景为红色
ctx.fillStyle = 'red'
//将颜色涂上去
ctx.fill()
//拓印到画布上
ctx.stroke()
</script>
不出意外在浏览器中就会出现如下效果图:
满天星
首先我们需要准备一张图片,为了让图像更有意境,这张图片放在landscape中。
- 在
body中放三个标签(第三个纯属就是为了增加一个动画效果)
<div class="landscape"></div>
<canvas id="canvas"></canvas>
<div class="filter"></div>
- 设置
css,让landscape和filter都相对body绝对定位,脱离文档流。
<style>
* {
margin: 0;
padding: 0;
}
html,
body {
width: 100%;
height: 100%;
}
body {
background: linear-gradient(to bottom, #000 0%, #5788fe 100%);
}
.landscape {
background: url('./xkbg.png');
background-repeat: repeat-x;
width: 100%;
height: 100%;
background-position: center bottom;
position: absolute;
top: 0;
left: 0;
}
.filter {
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
background: #fe5757;
animation: colorChange 30s ease-in-out infinite;
}
/* 增加动画模拟夜晚到天亮 */
@keyframes colorChange {
0%,
100% {
opacity: 0;
}
50% {
opacity: 0.5;
}
}
</style>
- 接下来就是重头戏了,
Js部分-星星我们用canvas画圆来实现它,位置随机地画出n个圆,然后展示在画布上。由于其他两层脱离了文档流,画布就会与其他两层重叠,显示出来图像。在这里我们用两段Js来实现它。
let canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d'),
initRoundPopulation = 80,
round = []
//设置画布的宽高与屏幕的宽和高相等
const WIDTH = document.documentElement.clientWidth,
HEIGHT = document.documentElement.clientHeight
canvas.width = WIDTH
canvas.height = HEIGHT
init()
function init() {
// 出现星星
for (let i = 0; i < initRoundPopulation; i++) {
// 批量生成80个对象
round[i] = new RoundItem(i, Math.random() * WIDTH, Math.random() * HEIGHT, ctx)
//递归调用
round[i].draw()
}
}
//构造函数
function RoundItem(index, x, y, ctx) {
this.index = index;
//点的x坐标,y坐标
this.x = x;
this.y = y;
this.ctx = ctx;
//半径
this.r = Math.random() * 2 + 1;
this.color = 'rgba(255,255,255,1)'
// this.draw = function () {
// //绘制
// }
}
//new RoundItem(1, 2, 3, 'ctx')
RoundItem.prototype.draw = function () {
//绘制
this.ctx.fillStyle = this.color;
this.ctx.beginPath();
this.ctx.arc(this.x, this.y, this.r, 0, 2 * Math.PI, false);
this.ctx.closePath();
this.ctx.fill();
}
这样就能看到满天星了,且有动画效果哟~
小结
Canvas在我们的日常开发中用得并不多,往往就是需要实现一个小东西的时候需要用到它。在这里其实也可以加一些炫酷的效果,比如流星啥的,都可以实现。最后感谢观看,创作不易,点个免费的赞吧,谢谢!