今天, 小编将与大家分享 web 前端特效荟萃系列第 20 期, 喜欢把玩儿炫酷效果的小伙伴快快看过来 ^_^ , 希望大家喜欢呦~
第 20 期, 给大家分享一个使用 CSS 生成的黑白动态二维码效果, 相关代码如下:
- <!doctype html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>cloth</title>
- <style>
- html, body {
- overflow: hidden;
- touch-action: none;
- content-zooming: none;
- position: absolute;
- margin: 0;
- padding: 0;
- width: 100%;
- height: 100%;
- background: #000;
- }
- canvas {
- position: absolute;
- width: 100vh;
- height: 100vh;
- max-height: 100vw;
- max-width: 100vw;
- margin: auto;
- top: 0;
- bottom: 0;
- left: 0;
- right: 0;
- user-select: none;
- cursor: pointer;
- }
- </style>
- </head>
- <body>
- <script>
- // http://exploringjs.com/es6/ch_generators.html
- // Adapted from https://www.contextfreeart.org/gallery2/index.html#design/1123
- "use strict";
- // grid
- function* grid(x, y, w, h) {
- if (w < 10) return;
- yield* box(x - w * 0.25, y - h * 0.25, w * 0.5, h * 0.5);
- yield* box(x + w * 0.25, y - h * 0.25, w * 0.5, h * 0.5);
- yield* box(x - w * 0.25, y + h * 0.25, w * 0.5, h * 0.5);
- yield* box(x + w * 0.25, y + h * 0.25, w * 0.5, h * 0.5);
- yield canvas.requestAnimationFrame(); // <---- pause RAF
- }
- // box rules
- function* box(x, y, w, h) {
- const r = Math.random() * 3.6;
- if (r < 0.1) {
- // nothing
- } else if (r < 0.5) {
- // yield new small grid
- yield* grid(x, y, w * 0.5, h * 0.5);
- } else if (r < 2.4) {
- // yield new grid
- yield* grid(x, y, w, h);
- } else {
- // draw square
- square(x, y, w, h, 0.8, "#fff");
- square(x, y, w, h, 0.6, "#000");
- }
- }
- // draw square
- function square(x, y, w, h, s, c) {
- ctx.fillStyle = c;
- ctx.fillRect(
- canvas.width * 0.5 + x - w * 0.5 + 0.5 * w * (1 - s),
- canvas.height * 0.5 + y - h * 0.5 + 0.5 * h * (1 - s),
- w * s,
- h * s
- );
- }
- // init canvas
- const canvas = {
- init() {
- this.elem = document.createElement("canvas");
- document.body.appendChild(this.elem);
- this.resize();
- return this.elem.getContext("2d");
- },
- resize() {
- const res = window.location.href.indexOf("fullcpgrid") > -1 ? 1 : 2;
- this.width = this.elem.width = this.elem.offsetWidth * res;
- this.height = this.elem.height = this.elem.offsetHeight * res;
- },
- requestAnimationFrame() {
- requestAnimationFrame(_ => gen.next());
- }
- };
- const ctx = canvas.init();
- // click / touch restart
- ["click", "touchdown"].forEach(event => {
- document.addEventListener(
- event,
- e => {
- // terminate generator
- gen.return();
- // clear screen
- canvas.resize();
- ctx.fillStyle = "#000";
- ctx.fillRect(0, 0, canvas.width, canvas.height);
- // restart
- gen = grid(0, 0, canvas.width, canvas.height);
- gen.next();
- },
- false
- );
- });
- // init generator
- let gen = grid(0, 0, canvas.width, canvas.height);
- // start iteration
- gen.next();
- // My brain hurts
- // My brain hurts
- // My brain hurts
- </script>
- </body>
- </html>
来源: http://igeekbar.com/igeekbar/post/1030.htm