小镜头全屏显示

2023-06-22  本文已影响0人  littlesunn
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="1400" height="700" style="border: 1px solid red"></canvas>
</body>

</html>
<script>

    // 工具类
    function getRotateVct(vct, angle) {
        let rad = angle * Math.PI / 180;
        let x1 = Math.cos(rad) * vct[0] - Math.sin(rad) * vct[1];
        let y1 = Math.sin(rad) * vct[0] + Math.cos(rad) * vct[1];
        return [x1, y1];  // 返回的是向量
    };

    function getMousePos(myCanvas, e) {
        let downX;
        let downY;
        if (e.x && e.y) {
            downX = e.x;
            downY = e.y;
        } else {
            downX = e.clientX;
            downY = e.clientY;
        }

        let { left, top } = myCanvas.getBoundingClientRect();

        let xDist = downX - left;
        let yDist = downY - top;

        return {
            x: xDist,
            y: yDist,
        };
    }
    // -------------------------------------

    // 常量
    const SOLIDCOLOR = '#CCCCCC70'; // 实线颜色
    const DASHEDCOLOR = '#CCCCCC25'; // 虚线颜色
    const ZEROCOLOR = '#358bf3'; // 0 点坐标系颜色
    const GRIDSIZE = 5;  // 一个正方形网格的宽高大小, 一个GRIDSIZE视为一个单位
    // -------------------------------------


    // 三角形点状元素
    class MyTriangle {

        constructor(x, y, width, height, angle = 0) {   // 相对坐标
            this.pointList = []
            this.x = x;
            this.y = y;
            this.width = width;
            this.height = height;
            this.angle = angle;
            this.isPointIn = false;
            this.fillStyle = "#69b1ff";
        }

        getPointsWithPosAndAngle(x, y, width, height) {
            let O = [x, y];
            let point1 = [x, y - height / 2];
            let point2 = [x - width / 2, y + height / 2];
            let point3 = [x + width / 2, y + height / 2];

            let vctp1 = [point1[0] - O[0], point1[1] - O[1]];
            let vctp2 = [point2[0] - O[0], point2[1] - O[1]];
            let vctp3 = [point3[0] - O[0], point3[1] - O[1]];

            let rvctp1 = getRotateVct(vctp1, this.angle);
            let rvctp2 = getRotateVct(vctp2, this.angle);
            let rvctp3 = getRotateVct(vctp3, this.angle);

            return [
                [rvctp1[0] + x, rvctp1[1] + y],
                [rvctp2[0] + x, rvctp2[1] + y],
                [rvctp3[0] + x, rvctp3[1] + y],
            ];
        }

        draw(ctx, x, y, width, height) {  // 真正绘制用像素坐标
            ctx.save();
            ctx.beginPath();
            this.getPointsWithPosAndAngle(x, y, width, height).forEach((p, i) => {
                if (i == 0) {
                    ctx.moveTo(p[0], p[1]);
                } else {
                    ctx.lineTo(p[0], p[1]);
                }
            })
            ctx.closePath();
            ctx.fillStyle = this.fillStyle;
            ctx.fill();
            this.setPointIn(ctx);
            ctx.restore();
        }

        setPointIn(ctx) {
            this.isPointIn = ctx.isPointInPath(GridSystem.currentMousePos.x, GridSystem.currentMousePos.y);
            if (!this.isPointIn) {
                this.fillStyle = "#69b1ff";
            } else {
                this.fillStyle = "#003eb3";
            }
        }
    }

    // 绘制类,主类
    class GridSystem {
        static currentMousePos = {
            x: 0,
            y: 0
        }

        constructor(canvasDom) {
            // 当前 canvas 的 0 0 坐标,我们设置 canvas 左上角顶点为 0 0,向右👉和向下👇是 X Y 轴正方向,0,0 为 pageSlicePos 初始值
            this.pageSlicePos = {
                x: 0,
                y: 0,
            };
            this.scale = 1; // 缩放比例
            this.myCanvas = canvasDom;
            this.ctx = this.myCanvas.getContext('2d');
            this.canvasWidth = this.ctx.canvas.width;
            this.canvasHeight = this.ctx.canvas.height;

            this.hoverNode = null;

            let triangle = new MyTriangle(600, 600, 50, 50);
            this.features = [
                triangle,
            ];

            this.firstPageSlicePos = Object.freeze({
                x: this.pageSlicePos.x,
                y: this.pageSlicePos.y
            });  // 记录一开始的的中心点坐标,不会改变的
            this.extent = [750, 800, 750, 800]  // 限制画布拖拽范围: 上右下左,顺时针
            this.initEventListener();

        }


        initEventListener() {
            this.myCanvas.addEventListener("mousemove", this.mouseMove.bind(this));
            this.myCanvas.addEventListener("mousedown", this.mouseDown.bind(this));
            this.myCanvas.addEventListener("mousewheel", this.mouseWheel.bind(this));
        }

        /**
 * 绘制网格
 */
        drawLineGrid = () => {
            // this.ctx.rotate(30)
            this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height);
            /*获取绘图工具*/
            // 设置网格大小
            var girdSize = this.getPixelSize(GRIDSIZE);
            // 获取Canvas的width、height
            var CanvasWidth = this.ctx.canvas.width;
            var CanvasHeight = this.ctx.canvas.height;

            // 在 pageSlicePos 的 x,y 点位画一个 10 * 10 的红色标记用来表示当前页面的 0 0 坐标
            this.ctx.fillRect(this.pageSlicePos.x, this.pageSlicePos.y, 10, 10); // 效果图红色小方块
            this.ctx.fillStyle = 'red';

            const canvasXHeight = CanvasHeight - this.pageSlicePos.y;
            const canvasYWidth = CanvasWidth - this.pageSlicePos.x;
            // 从 pageSlicePos.y 处开始往 Y 轴正方向画 X 轴网格
            const xPageSliceTotal = Math.ceil(canvasXHeight / girdSize);
            for (let i = 0; i < xPageSliceTotal; i++) {
                this.ctx.beginPath(); // 开启路径,设置不同的样式
                this.ctx.moveTo(0, this.pageSlicePos.y + girdSize * i);
                this.ctx.lineTo(CanvasWidth, this.pageSlicePos.y + girdSize * i);
                this.ctx.strokeStyle = i === 0 ? ZEROCOLOR : (i % 5 === 0 ? SOLIDCOLOR : DASHEDCOLOR); // 如果为 0 则用蓝色标记,取余 5 为实线,其余为比较淡的线
                this.ctx.stroke();
            }

            // 从 pageSlicePos.y 处开始往 Y 轴负方向画 X 轴网格
            const xRemaining = this.pageSlicePos.y;
            const xRemainingTotal = Math.ceil(xRemaining / girdSize);
            for (let i = 0; i < xRemainingTotal; i++) {
                if (i === 0) continue;
                this.ctx.beginPath(); // 开启路径,设置不同的样式
                this.ctx.moveTo(0, this.pageSlicePos.y - girdSize * i); // -0.5是为了解决像素模糊问题
                this.ctx.lineTo(CanvasWidth, this.pageSlicePos.y - girdSize * i);
                this.ctx.strokeStyle = i === 0 ? ZEROCOLOR : (i % 5 === 0 ? SOLIDCOLOR : DASHEDCOLOR);// 如果为 0 则用蓝色标记,取余 5 为实线,其余为比较淡的线
                this.ctx.stroke();
            }

            // 从 pageSlicePos.x 处开始往 X 轴正方向画 Y 轴网格
            const yPageSliceTotal = Math.ceil(canvasYWidth / girdSize); // 计算需要绘画y轴的条数
            for (let j = 0; j < yPageSliceTotal; j++) {
                this.ctx.beginPath(); // 开启路径,设置不同的样式
                this.ctx.moveTo(this.pageSlicePos.x + girdSize * j, 0);
                this.ctx.lineTo(this.pageSlicePos.x + girdSize * j, CanvasHeight);
                this.ctx.strokeStyle = j === 0 ? ZEROCOLOR : (j % 5 === 0 ? SOLIDCOLOR : DASHEDCOLOR);// 如果为 0 则用蓝色标记,取余 5 为实线,其余为比较淡的线
                this.ctx.stroke();
            }

            // 从 pageSlicePos.x 处开始往 X 轴负方向画 Y 轴网格
            const yRemaining = this.pageSlicePos.x;
            const yRemainingTotal = Math.ceil(yRemaining / girdSize);
            for (let j = 0; j < yRemainingTotal; j++) {
                if (j === 0) continue;
                this.ctx.beginPath(); // 开启路径,设置不同的样式
                this.ctx.moveTo(this.pageSlicePos.x - girdSize * j, 0);
                this.ctx.lineTo(this.pageSlicePos.x - girdSize * j, CanvasHeight);
                this.ctx.strokeStyle = j === 0 ? ZEROCOLOR : (j % 5 === 0 ? SOLIDCOLOR : DASHEDCOLOR);// 如果为 0 则用蓝色标记,取余 5 为实线,其余为比较淡的线
                this.ctx.stroke();
            }

            if (this.constructor.name == "GridSystem") {  // 如果是主类
                document.dispatchEvent(new CustomEvent("draw", { detail: this }));
            }
            this.drawFeatures();
        };


        /**
         * 滚轮缩放倍数
         */
        mouseWheel(e) {
            console.log(e.wheelDelta, " e");
            if (e.wheelDelta > 0) {
                if (this.scale < 10) {
                    this.scale++;
                }
            } else {
                if (this.scale > 1) {
                    this.scale--;
                }
            }
            this.drawLineGrid();
        }

        mouseMove(e) {
            GridSystem.currentMousePos.x = e.clientX;
            GridSystem.currentMousePos.y = e.clientY;
        }

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

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

        setPageSliceByExtent(extent = []) {
            if (extent?.length > 0) { // 限制拖拽范围
                let topExtent = extent[0];
                let rightExtent = extent[1];
                let bottomExtent = extent[2];
                let leftExtent = extent[3];

                if (this.pageSlicePos.x > this.firstPageSlicePos.x + leftExtent) {
                    this.pageSlicePos.x = this.firstPageSlicePos.x + leftExtent;
                }
                if (this.pageSlicePos.x < this.firstPageSlicePos.x - rightExtent) {
                    this.pageSlicePos.x = this.firstPageSlicePos.x - rightExtent;
                }
                if (this.pageSlicePos.y > this.firstPageSlicePos.y + topExtent) {
                    this.pageSlicePos.y = this.firstPageSlicePos.y + topExtent;
                }
                if (this.pageSlicePos.y < this.firstPageSlicePos.y - bottomExtent) {
                    this.pageSlicePos.y = this.firstPageSlicePos.y - bottomExtent;
                }
            }
        }

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

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

        getPixelSize(size) {
            return size * this.scale;
        }

        getRelativeSize(size) {
            return size / this.scale;
        }

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

        getRelativePosAndWH(x1, y1, width1, height1, block) {  // 元素的绝对坐标和大小
            let { x, y } = this.getRelativePos(
                { x: x1, y: y1 }, block
            );
            let width = this.getRelativeSize(width1, block)
            let height = this.getRelativeSize(height1, block)
            return { x, y, width, height }
        }

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


    // 小地图
    class MiniMap extends GridSystem {

        viewArea;  // 当前显示的区域
        isDragView;  // 是否正在渲染中
        parentGls;  // 主页面gls实例

        constructor(gls, width = 300, height = 170) {
            if (!gls.extent || gls.extent.length != 4) { throw new Error("主界面必须设置拖拽范围"); }
            let canvasDom = document.createElement("canvas");
            canvasDom.style.position = "fixed";
            canvasDom.style.border = "1px solid"
            canvasDom.style.backgroundColor = "#fff"
            canvasDom.width = width;
            canvasDom.height = height;
            document.body.appendChild(canvasDom)
            super(canvasDom);
            this.parentGls = gls;
            this.setMyCanvas(canvasDom);
            this.cbUpdateNodeProp = false;  // 设置小地图绘制元素时,不要更新元素的坐标宽高,不然会乱掉
            this.viewArea = {
                x: 0,
                y: 0,
                width: 0,
                height: 0
            }
            this.isDragView = false;
            this.setNodes();
        }

        setMyCanvas(canvasDom) {
            let { x, y, width, height } = this.parentGls.myCanvas.getBoundingClientRect();
            canvasDom.style.left = `${x + width - canvasDom.width - 10}px`
            canvasDom.style.top = `${y + height - canvasDom.height - 10}px`
        }

        initEventListener() {
            document.addEventListener("draw", this.drawMap.bind(this))
            this.myCanvas.addEventListener("mousedown", this.dragViewArea.bind(this))
        }

        drawMap() {
            this.drawLineGrid();
            if (!this.isDragView) {
                this.setViewAreaAndMapProp();
            }
            this.drawViewArea();
        }

        dragViewArea(e) {
            let { x, y } = getMousePos(this.myCanvas, e)
            let that = this;
            let glsTotalWidth = this.parentGls.extent[1] + this.parentGls.canvasWidth + this.parentGls.extent[3];
            let glsTotalHeight = this.parentGls.extent[0] + this.parentGls.canvasHeight + this.parentGls.extent[2];

            if (x > this.viewArea.x && x < this.viewArea.x + this.viewArea.width && y > this.viewArea.y && y < this.viewArea.y + this.viewArea.height) {
                this.isDragView = true;
                let vx = this.viewArea.x;
                let vy = this.viewArea.y;
                function mousemove(e) {
                    that.myCanvas.style.cursor = "move"
                    let { x: x1, y: y1 } = getMousePos(that.myCanvas, e);
                    let dx = vx + (x1 - x);
                    let dy = vy + (y1 - y);
                    that.viewArea.x = dx;
                    that.viewArea.y = dy;
                    // 判断是否超出边界
                    if (that.viewArea.x < 0) { that.viewArea.x = 0 };
                    if (that.viewArea.y < 0) { that.viewArea.y = 0 };
                    if (that.viewArea.x > that.canvasWidth - that.viewArea.width) { that.viewArea.x = that.canvasWidth - that.viewArea.width };
                    if (that.viewArea.y > that.canvasHeight - that.viewArea.height) { that.viewArea.y = that.canvasHeight - that.viewArea.height };
                    // 更新主页面中心坐标位置
                    that.parentGls.pageSlicePos.x = that.parentGls.extent[3] - (that.viewArea.x / that.canvasWidth * glsTotalWidth - that.parentGls.firstPageSlicePos.x);
                    that.parentGls.pageSlicePos.y = that.parentGls.extent[0] - (that.viewArea.y / that.canvasHeight * glsTotalHeight - that.parentGls.firstPageSlicePos.y);
                }
                function mouseup(e) {
                    that.myCanvas.style.cursor = "default"
                    that.isDragView = false;
                    document.removeEventListener("mousemove", mousemove)
                    document.removeEventListener("mouseup", mouseup)
                }
                document.addEventListener("mousemove", mousemove)
                document.addEventListener("mouseup", mouseup)
            } else {
                that.myCanvas.style.cursor = "default";
            }
        }

        setViewAreaAndMapProp() {
            // 主页面区域总宽高
            let glsTotalWidth = this.parentGls.extent[1] + this.parentGls.canvasWidth + this.parentGls.extent[3];
            let glsTotalHeight = this.parentGls.extent[0] + this.parentGls.canvasHeight + this.parentGls.extent[2];

            // 跟新小地图可视框
            this.viewArea.x = (this.parentGls.extent[3] - this.parentGls.pageSlicePos.x + this.parentGls.firstPageSlicePos.x) / glsTotalWidth * this.canvasWidth
            this.viewArea.y = (this.parentGls.extent[0] - this.parentGls.pageSlicePos.y + this.parentGls.firstPageSlicePos.y) / glsTotalHeight * this.canvasHeight
            this.viewArea.width = this.parentGls.canvasWidth / glsTotalWidth * this.canvasWidth
            this.viewArea.height = this.parentGls.canvasHeight / glsTotalHeight * this.canvasHeight

            // 设置小地图中心坐标与缩放大小
            this.scale = this.canvasWidth / (glsTotalWidth / this.parentGls.scale);
            this.pageSlicePos = {
                x: this.canvasWidth * ((this.parentGls.firstPageSlicePos.x + this.parentGls.extent[3]) / glsTotalWidth),
                y: this.canvasHeight * ((this.parentGls.firstPageSlicePos.y + this.parentGls.extent[0]) / glsTotalHeight)
            };
        }

        setNodes() {
            this.features = this.parentGls.features;
        }

        // 绘制可视范围rect
        drawViewArea() {
            this.ctx.beginPath();
            this.ctx.moveTo(this.viewArea.x, this.viewArea.y);
            this.ctx.lineTo(this.viewArea.x + this.viewArea.width, this.viewArea.y);
            this.ctx.lineTo(this.viewArea.x + this.viewArea.width, this.viewArea.y + this.viewArea.height);
            this.ctx.lineTo(this.viewArea.x, this.viewArea.y + this.viewArea.height);
            this.ctx.lineTo(this.viewArea.x, this.viewArea.y);
            this.ctx.fillStyle = "rgba(255,251,143,.5)"
            this.ctx.fill();
            this.ctx.closePath();
        }

        destory() {
            document.body.removeChild(this.myCanvas)
            document.removeEventListener("draw", this.drawMap)
            this.myCanvas.removeEventListener("mousedown", this.dragViewArea)
        }

    }

    let gls = new GridSystem(document.querySelector('#myCanvas'));
    let miniMap = new MiniMap(gls);

    (function main() {
        gls.drawLineGrid();
        requestAnimationFrame(main);
    })()

    document.addEventListener("keydown", (e) => {
        if (e.keyCode === 38) {
            gls.features[0].angle += 5;
        } else if (e.keyCode === 40) {
            gls.features[0].angle -= 5;
        }
    })

</script>
<style>
    body {
        margin: 0;
    }
</style>
上一篇下一篇

猜你喜欢

热点阅读