原理很简单, 刚学不久对 canvas 还有些不熟悉, 有什么可优化的地方可以留言 {:1_495:}
PS: 在做这个的时候还不知道 requestAnimationFrame, 用来代替 setInterval 也是不错. 文字其实可以直接设置基准线来对齐, 无需通过 context.measureText 计算 {:1_510:}
代码片段 1
- <!DOCTYPE html>
- <HTML lang="en" xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <meta charset="utf-8" />
- <title>
- Martrix
- </title>
- <style>
- body { margin: 0; padding: 0; background-color: #000; overflow: hidden;
- color:#e6922a; }
- </style>
- </head>
- <body>
- <canvas id="canvas">
- </canvas>
- <script type="text/javascript">
- var canvas = document.getElementById("canvas"),
- context = canvas.getContext("2d");
- var fontSize = 12,
- listText = "abcdefghijklmnopqrstuvwxyz".split(""),
- column,
- row,
- listColumn = [];
- function draw() {
- // 画背景
- context.fillStyle = "rgba(0, 0, 0, 0.05)";
- context.fillRect(0, 0, canvas.width, canvas.height);
- context.save();
- // 画 Logo
- context.shadowColor = "#074425";
- context.shadowBlur = parseInt(Math.random() * 40 + 1);
- context.font = "bold 36px Arial";
- context.fillStyle = "#eefbf5";
- context.fillText("MARTRIX", (canvas.width / 2 - context.measureText("MARTRIX").width / 2), canvas.height - 200);
- context.fillText("REVOLUTIONS", (canvas.width / 2 - context.measureText("REVOLUTIONS").width / 2), canvas.height - 150);
- context.font = "16px Microsoft Yahei";
- context.fillText("黑客帝国: 矩阵革命", (canvas.width / 2 - context.measureText("黑客帝国: 矩阵革命").width / 2), canvas.height - 100);
- // 画代码
- context.restore();
- context.font = "normal" + fontSize + "px Arial";
- context.fillStyle = "#12ee46";
- for (var i = 0; i < column; i++) {
- if (Math.random() > 0.5) {
- var str = listText[parseInt(Math.random() * listText.length)];
- context.fillText(str, i * fontSize, listColumn[i] * fontSize);
- listColumn[i] += 1;
- if (listColumn[i] >= row) {
- listColumn[i] = 0;
- }
- }
- }
- }
- function resize() {
- canvas.width = Windows.innerWidth - 3;
- canvas.height = Windows.innerHeight - 3;
- column = canvas.width / fontSize,
- row = canvas.height / fontSize;
- for (var i = 0; i < column; i++) {
- listColumn[i] = 1;
- }
- }
- Windows.addEventListener("resize", resize);
- canvas.addEventListener("mousedown",
- function() {
- clearInterval(timer);
- timer = setInterval(draw, 20);
- });
- canvas.addEventListener("mouseup",
- function() {
- clearInterval(timer);
- timer = setInterval(draw, 40);
- });
- resize();
- var timer = setInterval(draw, 40);
- </script>
- </body>
- </HTML>
来源: http://www.qdfuns.com/article/14978/e755d805c028a5a0773cffbe34562115.html