用canvas把页面中所有元素的轮廓绘制出来

复制代码
    function plot(){//绘制函数
        // 创建一个canvas画布
        const canvas=document.createElement("canvas");
        canvas.width=document.documentElement.offsetWidth;
        canvas.height=document.documentElement.offsetHeight;
        canvas.style.position='absolute';
        canvas.style.left="0";
        canvas.style.right="0";
        canvas.style.top="0";
        canvas.style.bottom="0";
        canvas.style.zIndex="99999";
        // 将画布添加到文档中
        document.body.appendChild(canvas);
        const ctx=canvas.getContext('2d');
        draw(ctx,getAllRects());
    }
    function draw(ctx,rects){
        let i=0;
        ctx.strokeStyle="red";
        window.requestAnimationFrame(_draw);//浏览器重绘前执行一下


        function _draw(){
            let{x,y,width,height}=rects[i++];
            ctx.strokeRect(x,y,width,height);
            if(i<rects.length){
                window.requestAnimationFrame(_draw);//1s重绘60次
            }else{
                console.log('dom元素遍历完了');
            }
        }
    }

    function getAllRects(){//获取页面内所有元素的函数,返回一个数组
        const allElements=document.querySelectorAll("*");//页面内所有元素
        const rects=[];
        const {x:htmlX,y:htmlY}=document.documentElement.getBoundingClientRect();//返回元素盒信息{x:x坐标,y:y坐标,width:宽度,height:高度}
        allElements.forEach(element => {
            const eachELRects=Array.from(element.getClientRects()).filter(rect=>{
                return rect.width||rect.height;
            }).map(rect=>{
                return {
                    x:rect.x-htmlX,
                    y:rect.y-htmlY,
                    width:rect.width,
                    height:rect.height
                }
            })
            rects.push(...eachELRects);
        });
        return rects;
    }
    plot();  
复制代码

 

posted @   古墩古墩  Views(1312)  Comments(0Edit  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示