用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();  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM