js画布封装之平铺(排版)
实现代码:
1 import { UTILS } from "./Utils.js"; 2 import { CanvasImageDraw, CanvasEvent, CanvasImageScroll, CanvasImageCustom } from "./ElementUtils.js"; 3 4 /* 测试封装 canvas 5 下载地址(无提取码, 2023.2.4 更新): https://www.123pan.com/s/ylTuVv-bfhpH 6 */ 7 function main(){ 8 9 //CanvasImage 的渲染器 10 const renderCI = new CanvasImageDraw({width: innerWidth, height: innerHeight}), 11 12 //CanvasImageDraw 的滚动条 13 scrollCI = new CanvasImageScroll(renderCI, {scrollSize: 8}), 14 15 //CanvasImage 的事件运行类 16 eventCI = new CanvasEvent(renderCI), 17 18 shadow = {blur: 5, color: "#666666", offsetX: 2, offsetY: 5}, 19 20 onup = v => { 21 if(v.delta < 600){ 22 v.target.clear().fill("#333333").fillText(String(renderCI.list.indexOf(v.target)), "#cccccc"); 23 renderCI.redraw(); 24 cic.removeEventListener("up", onup); 25 } 26 } 27 28 //批量创建 CanvasImage 29 for(let i = 0; i < 10000; i++){ 30 const cic = new CanvasImageCustom() 31 .size(UTILS.random(10, 100), UTILS.random(10, 100)) 32 .fillRect(`rgb(${UTILS.random(0,255)}, ${UTILS.random(0,255)}, ${UTILS.random(0,255)})`) 33 .fillText(String(i), "#000000"); 34 cic.opacity = UTILS.random(0, 1); 35 cic.shadow = shadow; 36 37 //scrollCI.bindScroll(ci: CanvasImage) 方法可以使滚动条(scrollCI)能够监听ci的位置和ci.visible属性的变化来更新滚动条 38 //scrollCI.changeCIAdd(ci: CanvasImage) 方法根据ci主动更新一次滚动条 39 scrollCI.bindScroll(cic); 40 scrollCI.changeCIAdd(cic); 41 42 //加入到渲染器(renderCI)队列 43 renderCI.list[i] = cic; 44 45 //添加鼠标事件 46 cic.addEventListener("up", onup); 47 } 48 49 //平铺排序(向下看齐)和添加至dom树 50 renderCI.sortCIPos(null, {disX: 10, disY: 10, lineHeight: "bottom"}) 51 .render(document.body); 52 53 //退出: 54 //scrollCI.unbindEvent(); 55 //canvasEvent.unbindEvent(); 56 //renderCI.exit(); 57 console.log(renderCI, scrollCI); 58 59 } 60 61 main();
结果视图:
下载地址(无提取码, 2023.2.4 更新): https://www.123pan.com/s/ylTuVv-bfhpH
运行 GoServer.exe 然后打开浏览器输入 http://localhost:8080/