臨近下班來一發,讓你在地鐵上就能理解canvas離屏緩存html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
* {
padding: 0;
margin: 0;
}
</style>
</head>
<body>
<p>
F12,ctrl+shift+p搜索FPS,打開fps顯示數值
</p>
<canvas id='canvas' width="800" height="600">瀏覽器不支持canvas</canvas>
</body>
<script>
var canvas = document.getElementById("canvas")
var ctx = canvas.getContext('2d')
var isCache = true //是否開啓離線緩存,改成false試試?
var borderWidth = 2
var Balls = []
var Ball = function (x, y, vx, vy, useCache) {
this.x = x;
this.y = y;
this.vx = vx;
this.vy = vy;
this.r = getZ(getRandom(20, 40));
this.color = [];
//爲了體現性能專門繁瑣的畫圈圈
var num = getZ(this.r / borderWidth);
for (var j = 0; j < num; j++) {
this.color.push("rgba(" + getZ(getRandom(0, 255)) + "," + getZ(getRandom(0, 255)) + "," + getZ(getRandom(0, 255)) + ",1)");
}
//核心代碼
this.cacheCanvas = document.createElement("canvas");
this.cacheCtx = this.cacheCanvas.getContext("2d");
this.cacheCanvas.width = 2 * this.r;
this.cacheCanvas.height = 2 * this.r;
// document.body.appendChild(this.cacheCanvas)
this.useCache = useCache;
if (useCache) {
this.cache();
}
}
Ball.prototype = {
paint: function (ctx) {
if (!this.useCache) {
ctx.save();
var j = 0;
ctx.lineWidth = borderWidth;
for (var i = 1; i < this.r; i += borderWidth) {
ctx.beginPath();
ctx.strokeStyle = this.color[j];
ctx.arc(this.x, this.y, i, 0, 2 * Math.PI);
ctx.stroke();
j++;
}
ctx.restore();
} else {
ctx.drawImage(this.cacheCanvas, this.x - this.r, this.y - this.r);
}
},
cache: function () {
ctx.save();
var j = 0;
this.cacheCtx.lineWidth = borderWidth;
for (var i = 1; i < this.r; i += borderWidth) {
this.cacheCtx.beginPath();
this.cacheCtx.strokeStyle = this.color[j];
this.cacheCtx.arc(this.r, this.r, i, 0, 2 * Math.PI);
this.cacheCtx.stroke();
j++;
}
ctx.restore();
},
move: function () {
this.paint(ctx);
this.x += this.vx;
this.y += this.vy;
if (this.x > (canvas.width - this.r) || this.x < this.r) {
this.x = this.x < this.r ? this.r : (canvas.width - this.r);
this.vx = -this.vx;
}
if (this.y > (canvas.height - this.r) || this.y < this.r) {
this.y = this.y < this.r ? this.r : (canvas.height - this.r);
this.vy = -this.vy;
}
}
}
function init() {
Balls.length = 0
for (var i = 0; i < 50; i++) {
var ball = new Ball(getRandom(0, canvas.width), getRandom(0, canvas.height), getRandom(-5, 5), getRandom(-5, 5), isCache)
Balls.push(ball);
}
update();
}
function update() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < Balls.length; i++) {
Balls[i].move();
}
requestAnimationFrame(update)
}
function getZ(num) {
//返回整數對性能有優化
return ~~num;
}
function getRandom(a, b) {
return Math.random() * (b - a) + a;
}
init()
</script>
</html>
複製代碼