canvas 網(wǎng)格畫布以鼠標中心點放大縮小

image.png
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <canvas id="myCanvas" width="1080" height="630"></canvas>
</body>

</html>
<script>
    class MyRect {

        constructor(x, y, width, height) {   // 相對坐標
            this.x = x;
            this.y = y;
            this.width = width;
            this.height = height;
            this.isPointIn = false;
            this.fillColor = "#69b1ff";
        }

        draw(ctx, x, y, width, height) {  // 真正繪制用像素坐標
            ctx.save();
            ctx.beginPath();
            ctx.moveTo(x, y);
            ctx.lineTo(x + width, y);
            ctx.lineTo(x + width, y + height);
            ctx.lineTo(x, y + height);
            ctx.closePath();
            ctx.fillStyle = this.fillColor;
            ctx.fill();
            this.hasPointIn(ctx);
            ctx.restore();
        }

        hasPointIn(ctx) {
            this.isPointIn = ctx.isPointInPath(curMousePos.x, curMousePos.y);
            if (!this.isPointIn) {
                this.fillColor = "#69b1ff";
            } else {
                this.fillColor = "#003eb3";
            }
        }

        // setPointIsIn(isPointIn){
        //     this.isPointIn = isPointIn;
        // }

    }

    // 當前 canvas 的 0 0 坐標,我們設置 canvas 左上角頂點為 0 0,向右??和向下??是 X Y 軸正方向,0,0 為 pageSlicePos 初始值
    const pageSlicePos = {
        x: 0,
        y: 0,
    };
    var scale = 10; // 縮放比例
    const solidColor = '#CCCCCC70'; // 實線顏色
    const dashedColor = '#CCCCCC25'; // 虛線顏色
    const zeroColor = '#358bf3'; // 0 點坐標系顏色
    const myCanvas = document.querySelector('#myCanvas');
    const GRIDSIZE = 5;  // 一個正方形網(wǎng)格的寬高大小, 一個GRIDSIZE視為一個單位
    const ctx = myCanvas.getContext('2d');
    const curMousePos = {
        x: 0,
        y: 0
    }
    var hoverNode = null;

    var lastGirdSize = 0;
    var lastPageSlicePos2scale = {
        x: pageSlicePos.x,
        y: pageSlicePos.y,
    };

    myCanvas.addEventListener("mousemove", mouseMove);
    myCanvas.addEventListener("mousedown", mouseDown);
    myCanvas.addEventListener("mousewheel", mouseWheel);
    let features = [
        new MyRect(50, 50, 10, 10),
    ];
    setInterval(() => {
        drawLineGrid();
        drawFeature();
    }, 0);

    /**
     * 繪制網(wǎng)格
     * @param scaleVal 縮放倍數(shù)
     */
    var drawLineGrid = (scaleVal = scale) => {
        ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
        /*獲取繪圖工具*/
        // 設置網(wǎng)格大小
        var girdSize = getPixelSize(GRIDSIZE);
        lastGirdSize = girdSize;  // 記錄上一次的gridSize
        // 獲取Canvas的width、height
        var CanvasWidth = ctx.canvas.width;
        var CanvasHeight = ctx.canvas.height;

        // 在 pageSlicePos 的 x,y 點位畫一個 10 * 10 的紅色標記用來表示當前頁面的 0 0 坐標
        ctx.fillRect(pageSlicePos.x, pageSlicePos.y, 10, 10); // 效果圖紅色小方塊
        ctx.fillStyle = 'red';

        const canvasXHeight = CanvasHeight - pageSlicePos.y;
        const canvasYWidth = CanvasWidth - pageSlicePos.x;
        // 從 pageSlicePos.y 處開始往 Y 軸正方向畫 X 軸網(wǎng)格
        const xPageSliceTotal = Math.ceil(canvasXHeight / girdSize);
        for (let i = 0; i < xPageSliceTotal; i++) {
            ctx.beginPath(); // 開啟路徑,設置不同的樣式
            ctx.moveTo(0, pageSlicePos.y + girdSize * i);
            ctx.lineTo(CanvasWidth, pageSlicePos.y + girdSize * i);
            ctx.strokeStyle = i === 0 ? zeroColor : (i % 5 === 0 ? solidColor : dashedColor); // 如果為 0 則用藍色標記,取余 5 為實線,其余為比較淡的線
            ctx.stroke();
        }

        // 從 pageSlicePos.y 處開始往 Y 軸負方向畫 X 軸網(wǎng)格
        const xRemaining = pageSlicePos.y;
        const xRemainingTotal = Math.ceil(xRemaining / girdSize);
        for (let i = 0; i < xRemainingTotal; i++) {
            if (i === 0) continue;
            ctx.beginPath(); // 開啟路徑,設置不同的樣式
            ctx.moveTo(0, pageSlicePos.y - girdSize * i); // -0.5是為了解決像素模糊問題
            ctx.lineTo(CanvasWidth, pageSlicePos.y - girdSize * i);
            ctx.strokeStyle = i === 0 ? zeroColor : (i % 5 === 0 ? solidColor : dashedColor);// 如果為 0 則用藍色標記,取余 5 為實線,其余為比較淡的線
            ctx.stroke();
        }

        // 從 pageSlicePos.x 處開始往 X 軸正方向畫 Y 軸網(wǎng)格
        const yPageSliceTotal = Math.ceil(canvasYWidth / girdSize); // 計算需要繪畫y軸的條數(shù)
        for (let j = 0; j < yPageSliceTotal; j++) {
            ctx.beginPath(); // 開啟路徑,設置不同的樣式
            ctx.moveTo(pageSlicePos.x + girdSize * j, 0);
            ctx.lineTo(pageSlicePos.x + girdSize * j, CanvasHeight);
            ctx.strokeStyle = j === 0 ? zeroColor : (j % 5 === 0 ? solidColor : dashedColor);// 如果為 0 則用藍色標記,取余 5 為實線,其余為比較淡的線
            ctx.stroke();
        }

        // 從 pageSlicePos.x 處開始往 X 軸負方向畫 Y 軸網(wǎng)格
        const yRemaining = pageSlicePos.x;
        const yRemainingTotal = Math.ceil(yRemaining / girdSize);
        for (let j = 0; j < yRemainingTotal; j++) {
            if (j === 0) continue;
            ctx.beginPath(); // 開啟路徑,設置不同的樣式
            ctx.moveTo(pageSlicePos.x - girdSize * j, 0);
            ctx.lineTo(pageSlicePos.x - girdSize * j, CanvasHeight);
            ctx.strokeStyle = j === 0 ? zeroColor : (j % 5 === 0 ? solidColor : dashedColor);// 如果為 0 則用藍色標記,取余 5 為實線,其余為比較淡的線
            ctx.stroke();
        }
    };

    /**
     * 滾輪縮放倍數(shù)
     */
    function mouseWheel(e) {
        let [x, y] = [e.clientX, e.clientY];
        if (e.wheelDelta > 0) {
            if (scale < 10) {
                scale++;
                back2center(x, y);
            }
        } else {
            if (scale > 1) {
                scale--;
                back2center(x, y);
            }
        }
    }

    // 以鼠標中心點位置去放大
    function back2center(x, y) {
        var girdSize = getPixelSize(GRIDSIZE);  // 當前單位大小
        var different = girdSize - lastGirdSize;   // 當前單位大小與上一次單位大小之差
        pageSlicePos.x -= ((x - lastPageSlicePos2scale.x) / lastGirdSize) * different;
        pageSlicePos.y -= ((y - lastPageSlicePos2scale.y) / lastGirdSize) * different;

        // lastGirdSize = getPixelSize(GRIDSIZE);
        lastPageSlicePos2scale.x = pageSlicePos.x;
        lastPageSlicePos2scale.y = pageSlicePos.y;
    }

    function mouseMove(e) {
        curMousePos.x = e.clientX;
        curMousePos.y = e.clientY;
    }

    /**
     * 拖動 canvas 動態(tài)渲染,拖動時,動態(tài)設置 pageSlicePos 的值
     * @param e Event
     */
    function mouseDown(e) {
        const downX = e.clientX;
        const downY = e.clientY;
        const { x, y } = pageSlicePos;
        hoverNode = features.find(f => f.isPointIn && f);
        if (hoverNode) {
            let { x: fx, y: fy } = hoverNode;
            document.onmousemove = (ev) => {
                const moveX = ev.clientX;
                const moveY = ev.clientY;
                let { x: x1, y: y1 } = getRelativePos({ x: downX, y: downY })
                let { x: x2, y: y2 } = getRelativePos({ x: moveX, y: moveY })

                hoverNode.x = fx + (x2 - x1);
                hoverNode.y = fy + (y2 - y1);
                myCanvas.onmouseup = (en) => {
                    document.onmousemove = null;
                    myCanvas.onmouseup = null;
                };
            }
        } else {
            document.onmousemove = (ev) => {
                const moveX = ev.clientX;
                const moveY = ev.clientY;
                pageSlicePos.x = x + (moveX - downX);
                pageSlicePos.y = y + (moveY - downY);
                myCanvas.onmouseup = (en) => {
                    document.onmousemove = null;
                    myCanvas.onmouseup = null;
                };
            }
        }


        myCanvas.onmouseup = (en) => {
            myCanvas.onmousemove = null;
            myCanvas.onmouseup = null;
        };
    }

    function getPixelPos(point, block) {
        return {
            x: pageSlicePos.x + (point.x / GRIDSIZE) * scale,
            y: pageSlicePos.y + (point.y / GRIDSIZE) * scale,
        };
    }

    function getRelativePos(point, block) {
        return {
            x: ((point.x - pageSlicePos.x) / scale) * GRIDSIZE,
            y: ((point.y - pageSlicePos.y) / scale) * GRIDSIZE,
        };
    }

    function getPixelSize(size) {
        return size * scale;
    }

    function getRelativeSize(size) {
        return size / scale;
    }

    function getPixelPosAndWH(block) {  // 元素的像素坐標和大小
        let { x, y } = getPixelPos(block, block);
        var width = getPixelSize(block.width, block);
        var height = getPixelSize(block.height, block);
        return { x, y, width, height, }
    }

    function getRelativePosAndWH(x1, y1, width1, height1, block) {  // 元素的絕對坐標和大小
        let { x, y } = getRelativePos(
            { x: x1, y: y1 }, block
        );
        let width = getRelativeSize(width1, block)
        let height = getRelativeSize(height1, block)
        return { x, y, width, height }
    }

    function drawFeature() {
        features.forEach(f => {
            let { x, y, width, height } = getPixelPosAndWH(f);
            f.draw(ctx, x, y, width, height)
        })
    }


</script>

學習更多canvas高級技巧,可以訪問我的課堂: https://www.bilibili.com/cheese/play/ss19337

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容