|
|
请马上登录,朋友们都在花潮里等着你哦:)
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 马黑黑 于 2023-12-24 20:13 编辑
去年八月份做的一个帖子,《黑客帝国》,当时没有引入代码雨可控机制。那时的JS代码是酱紫:
<script type="text/javascript">
let ctx = canv.getContext('2d');
let w = canv.width, h = canv.height;
let texts = Array.from(Array(94), (x,k) => String.fromCharCode(33+k)),
fontsize = 16,
columns = Math.floor(w / fontsize) - 1,
drops = new Array(columns),
aud = new Audio();
aud.src = 'https://music.163.com/song/media/outer/url?id=1809135506.mp3';
aud.loop = true;
aud.autoplay = true;
disc.style.animationPlayState = aud.paused ? 'paused' : 'running';
disc.onclick = () => aud.paused ? aud.play() : aud.pause();
aud.addEventListener('playing',() => disc.style.animationPlayState = 'running');
aud.addEventListener('pause',() => disc.style.animationPlayState = 'paused');
(function draw(){
ctx.fillStyle = 'rgba(0, 0, 0, 0.1)';
ctx.fillRect(0, 0, w, h);
ctx.fillStyle = '#0f0';
ctx.font = fontsize + 'px arial';
for(var j = 0; j < drops.length; j ++){
let text = texts[Math.floor(Math.random() * texts.length)];
ctx.fillText(text, j * fontsize + fontsize / 2 + 1, drops[j] * fontsize);
if(drops[j]*fontsize > h || Math.random() > 0.95){
drops[j] = 0;
}
drops[j]++;
}
requestAnimationFrame(draw);
})();
</script>
我们改变一下,不是大刀阔斧的改变:
<script type="text/javascript">
let cTimer = null;
let ctx = canv.getContext('2d');
let w = canv.width, h = canv.height;
let texts = Array.from(Array(94), (x,k) => String.fromCharCode(33+k)),
fontsize = 16,
columns = Math.floor(w / fontsize) - 1,
drops = new Array(columns),
aud = new Audio();
aud.src = 'https://music.163.com/song/media/outer/url?id=1809135506';
aud.loop = true;
aud.autoplay = true;
let mState = () => {
disc.style.animationPlayState = aud.paused ? 'paused' : 'running';
draw();
};
disc.onclick = () => aud.paused ? aud.play() : aud.pause();
aud.addEventListener('playing',mState,false);
aud.addEventListener('pause',mState,false);
function draw() {
ctx.fillStyle = 'rgba(0, 0, 0, 0.1)';
ctx.fillRect(0, 0, w, h);
ctx.fillStyle = '#0f0';
ctx.font = fontsize + 'px arial';
for(var j = 0; j < drops.length; j ++){
let text = texts[Math.floor(Math.random() * texts.length)];
ctx.fillText(text, j * fontsize + fontsize / 2 + 1, drops[j] * fontsize);
if(drops[j]*fontsize > h || Math.random() > 0.95){
drops[j] = 0;
}
drops[j]++;
}
cTimer = aud.paused ? cancelAnimationFrame(cTimer) : requestAnimationFrame(draw);
};
</script>
一个 cTimer 变量,用来标记请求关键帧动画执行状态;设计一个我们已经习以为常的 mState 函数,作为控制按钮和代码雨的触发机制;两个 audio 监听事件,绑定 mState 函数;最后是,原来的自执行函数 draw 去掉外壳,不自动执行(它由 mState 函数带动执行,mState 执行的是 draw 函数,draw 函数又由 audio 控件的暂停与否做判断、决定是否运行代码雨)。
|
评分
-
| 参与人数 2 | 威望 +80 |
金钱 +160 |
经验 +80 |
收起
理由
|
千羽
| + 30 |
+ 60 |
+ 30 |
很给力! |
红影
| + 50 |
+ 100 |
+ 50 |
赞一个! |
查看全部评分
|