canvas初学demo留存
看了canvas的掘金小册 写的demo留存
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>canvas初学demo留存</title>
<style>
#canvas, #canvas2 {
position: absolute;
top: 0px;
left: 0px;
}
#canvas {
background: #000;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<canvas id="canvas2"></canvas>
</body>
<script>
var ctx = document.getElementById('canvas'),
ctx2 = document.getElementById('canvas2'),
content = ctx.getContext('2d'),
content2 = ctx2.getContext('2d'),
WIDTH,
HEIGHT,
round = [],
initRoundPopulation = 4,
i = 1.5 * Math.PI,
step = 0.01,
lineWidth = 3;
WIDTH = document.documentElement.clientWidth;
HEIGHT = document.documentElement.clientHeight;
ctx.width = WIDTH;
ctx.height = HEIGHT;
ctx2.width = WIDTH;
ctx2.height = HEIGHT;
// 创建随机单例 类
function RoundItem(index, x, y) {
this.index = index;
this.x = x;
this.y = y;
this.r = Math.random() * 25 + 50;
var alpha = (Math.floor(Math.random() * 10) + 1) / 10 / 2; //透明度
var r = Math.floor(Math.random() * 256);
var g = Math.floor(Math.random() * 256);
var b = Math.floor(Math.random() * 256);
this.color = "rgba(" + r + "," + g + "," + b + "," + alpha + ")";
}
// 给RoundItem添加draw()方法
RoundItem.prototype.draw = function () {
content.strokeStyle = this.color;
// content.fillStyle = this.color;
content.showBlur = this.r * 2;
content.lineWidth = lineWidth;
content.beginPath();
content.arc(this.x, this.y, this.r, Math.PI * 0.5, Math.PI * 1.5, false);
content.stroke()
/* content2.beginPath();
content2.arc(this.x ,this.y+this.r, 1, 0, 2 * Math.PI, false);
content2.fillStyle ='#fff';
content2.closePath();
content2.fill()*/
}
// 给RoundItem添加move()方法
var isBottom = false
var isTop = false
RoundItem.prototype.move = function () {
if (isBottom) {
this.r += 0.2
this.y -= 0.2
if (this.y <= 100) {
isBottom = false
}
} else {
this.r -= 0.2
this.y += 0.2
if (this.y >= 120) {
isBottom = true
}
}
if (!isTop) {
i += step
if (i >= Math.PI * 2.5) {
isTop = true
}
} else {
i -= step
if (i <= Math.PI * 1.5) {
isTop = false
}
}
var C = [this.x, this.y];
var x = C[0] - this.r * Math.cos(i);
var y = C[1] - this.r * Math.sin(i);
content2.beginPath();
content2.arc(x, y, lineWidth / 2, 0, 2 * Math.PI, false);
content2.fillStyle = '#fff';
content2.closePath();
content2.fill()
this.draw();
}
// 初始化init函数
function init() {
for (var i = 0; i < initRoundPopulation; i++) {
round[i] = new RoundItem(i, 100, 100);
round[i].draw();
}
animate();
}
// 粒子运动函数
function animate() {
content.clearRect(0, 0, WIDTH, HEIGHT)// 每次运动前清除去画布
content2.clearRect(0, 0, WIDTH, HEIGHT)// 每次运动前清除去画布
for (var i in round) {
round[i].move()
}
//window.requestAnimationFrame() 方法告诉浏览器,
// 你希望执行动画,并请求浏览器调用指定的函数在下一次重绘之前更新动画。
// 该方法使用一个回调函数作为参数,这个回调函数会在浏览器重绘之前调用。
// 这里使用requestAnimationFrame() 函数递归的调用 animate() 函数来实现动画的效果。
requestAnimationFrame(animate);
}
init()
</script>
</html>