canvas画布元素间曲线连接以及全屏截图

视频演示讲解 https://www.bilibili.com/video/BV1Q8411m7Yh/

<!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>
    <button id="btn">大范围截图</button>
</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 getVctLen([x, y]) {
        return Math.sqrt(x * x + y * y);
    };

    /**
* 根据点在向量上的比例计算点坐标, [xO, yO]为起点,[xVct, yVct]为向量,k 为该点在向量方向上的长度
* 获取
*/
    function getPntInVct([xO, yO], [xVct, yVct], k) {
        let lenVct = getVctLen([xVct, yVct]);  // 获取向量长度
        let stdVct;
        if (lenVct === 0) {
            stdVct = [0, 0];
        } else {
            stdVct = [xVct / lenVct, yVct / lenVct];   // 单位向量
        }
        return [xO + k * stdVct[0], yO + k * stdVct[1]];
    };


    vct = function (start, end) {
        let x = end[0] - start[0];
        let y = end[1] - start[1];
        return [x, y];
    };

    /**
 * P 绕 O 点逆时针旋转angle角度后得到新的点坐标
 */
    getRotatePnt = function (O, P, angle) {
        if (angle === 0) {
            return P;
        }
        let vctOP = vct(O, P),
            OP = getVctLen(vctOP);
        let dvctOQ = getRotateVct(vctOP, angle);
        let newPoint = getPntInVct(O, dvctOQ, OP);
        return newPoint;
    };

    /**
* 在一段三次贝塞尔曲线上均匀取点, 不包括终点
* @param counts 一段贝塞尔曲线中取点的数量
*/
    getPntsOf3Bezier = function (p0, p1, p2, p3, counts) {
        let per = counts && counts != 0 ? 1 / counts : 0.02;    //取点间隔
        let points = [];
        for (let t = 0; t <= 0.999999; t += per) {
            points.push(getPntIn3Bezier(p0, p1, p2, p3, t));
        }
        return points;
    };

    /**
     * 获取三次贝塞尔曲线上的一点,t∈[0,1]
     * @param t 介于0 ~ 1, 表示点在曲线中的相对位置
     */
    getPntIn3Bezier = function (p0, p1, p2, p3, t) {
        let t_ = 1 - t;
        let x = p0[0] * t_ * t_ * t_ + 3 * p1[0] * t * t_ * t_ + 3 * p2[0] * t * t * t_ + p3[0] * t * t * t,
            y = p0[1] * t_ * t_ * t_ + 3 * p1[1] * t * t_ * t_ + 3 * p2[1] * t * t * t_ + p3[1] * t * t * t;
        return [x, y];
    };


    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 = 2;  // 一个正方形网格的宽高大小, 一个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 Link {

        startNode = [];
        endNode = [];

        constructor(startNode, endNode) {
            this.startNode = startNode;
            this.endNode = endNode;
        }

        draw(ctx, startPos, endPos) {
            let vct = [endPos.x - startPos.x, endPos.y - startPos.y];
            let cp1 = getPntInVct([startPos.x, startPos.y], vct, getVctLen(vct) * 0.4);
            let cp2 = getPntInVct([startPos.x, startPos.y], vct, getVctLen(vct) * 0.6);
            let rcp1 = getRotatePnt([startPos.x, startPos.y], cp1, 25);
            let rcp2 = getRotatePnt([endPos.x, endPos.y], cp2, 25);
            let points = getPntsOf3Bezier([startPos.x, startPos.y], rcp1, rcp2, [endPos.x, endPos.y], 50);

            ctx.save();
            ctx.beginPath();

            points.forEach((p, i) => {
                if (i == 0) {
                    ctx.moveTo(p[0], p[1]);
                } else {
                    ctx.lineTo(p[0], p[1]);
                }
            })

            ctx.lineWidth = 3;
            ctx.strokeStyle = "#fc0"
            ctx.stroke();
            ctx.closePath();
            ctx.restore();
        }

    }

    // 绘制类,主类
    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);
            let triangle2 = new MyTriangle(1800, 1800, 50, 50);
            let line = new Link(triangle, triangle2);

            this.features = [
                triangle,
                triangle2,

            ];
            this.lines = [
                line,
            ]

            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 < 5) {
                    this.scale++;
                }
            } else {
                if (this.scale > .2) {
                    this.scale -= .1;
                }
            }
            console.log(this.scale, "scale");
        }

        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);
                    document.onmouseup = (en) => {
                        document.onmousemove = null;
                        document.onmouseup = null;
                    };
                }
            }
        }

        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);
            })
            this.lines.forEach(f => {
                f.draw(this.ctx, this.getPixelPosAndWH(f.startNode), this.getPixelPosAndWH(f.endNode));
            })
        }
    }

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

    btn.onclick = () => {
        let canvas2 = document.createElement('canvas');
        canvas2.width = 3000;
        canvas2.height = 1800;
        let gls2 = new GridSystem(canvas2);
        gls2.features = gls.features;
        gls2.lines = gls.lines;
        gls2.scale = .5;
        gls2.pageSlicePos.x = gls2.ctx.canvas.width / 2;
        gls2.pageSlicePos.y = gls2.ctx.canvas.height / 2;
        gls2.drawLineGrid();
        let base64Str = canvas2.toDataURL("png", 1);

        let aLink = document.createElement("a");
        aLink.style.display = "none";
        aLink.href = base64Str;
        aLink.download = "截图.png";
        // 触发点击-然后移除
        document.body.appendChild(aLink);
        aLink.click();
        document.body.removeChild(aLink);
        canvas2 = null;
        gls2 = null;
    }

    (function main() {
        gls.drawLineGrid();
        gls.features[0].x += 1.5
        requestAnimationFrame(main);
    })()


</script>
<style>
    body {
        margin: 0;
    }
</style> 
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,165评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,720评论 1 298
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,849评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,245评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,596评论 3 288
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,747评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,977评论 2 315
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,708评论 0 204
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,448评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,657评论 2 249
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,141评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,493评论 3 258
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,153评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,108评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,890评论 0 198
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,799评论 2 277
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,685评论 2 272

推荐阅读更多精彩内容