美文网首页
canvas 元素的缩放旋转-向量方式

canvas 元素的缩放旋转-向量方式

作者: littlesunn | 来源:发表于2023-06-07 09:13 被阅读0次
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>
    <button id="addWidth">宽度++</button>
    <button id="addHeight">高度++</button>
    <button id="addAngle">角度++</button>
    <button id="minusAngle">角度--</button>
</body>

</html>
<script>

    getRotateVct = function (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];  // 返回的是向量
    };

    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(curMousePos.x, curMousePos.y);
            if (!this.isPointIn) {
                this.fillStyle = "#69b1ff";
            } else {
                this.fillStyle = "#003eb3";
            }
        }
    }

    // 当前 canvas 的 0 0 坐标,我们设置 canvas 左上角顶点为 0 0,向右👉和向下👇是 X Y 轴正方向,0,0 为 pageSlicePos 初始值
    const pageSlicePos = {
        x: 0,
        y: 0,
    };
    var scale = 1; // 缩放比例
    const solidColor = '#CCCCCC70'; // 实线颜色
    const dashedColor = '#CCCCCC25'; // 虚线颜色
    const zeroColor = '#358bf3'; // 0 点坐标系颜色
    const myCanvas = document.querySelector('#myCanvas');
    const GRIDSIZE = 5;  // 一个正方形网格的宽高大小, 一个GRIDSIZE视为一个单位
    const ctx = myCanvas.getContext('2d');
    const curMousePos = {
        x: 0,
        y: 0
    }
    var hoverNode = null;

    myCanvas.addEventListener("mousemove", mouseMove);
    myCanvas.addEventListener("mousedown", mouseDown);
    myCanvas.addEventListener("mousewheel", mouseWheel);

    let triangle = new MyTriangle(600, 600, 50, 50);
    addWidth.onclick = () => {
        triangle.width+=4;
    }
    addAngle.onclick = () => {
        triangle.angle+=4;
    }
    addHeight.onclick = ()=>{
        triangle.height+=4;
    }
    minusAngle.onclick = ()=>{
        triangle.angle-=4;
    }
    let features = [
        triangle,
    ];
    setInterval(() => {
        drawLineGrid();
        drawFeature();
    }, 0);

    /**
     * 绘制网格
     * @param scaleVal 缩放倍数
     */
    var drawLineGrid = (scaleVal = scale) => {
        ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
        /*获取绘图工具*/
        // 设置网格大小
        var girdSize = getPixelSize(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 轴网格
        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 轴网格
        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 轴网格
        const yPageSliceTotal = Math.ceil(canvasYWidth / girdSize); // 计算需要绘画y轴的条数
        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 轴网格
        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();
        }
    };

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

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

    /**
     * 拖动 canvas 动态渲染,拖动时,动态设置 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;
            myCanvas.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) => {
                    myCanvas.onmousemove = null;
                    myCanvas.onmouseup = null;
                };
            }
        } else {
            myCanvas.onmousemove = (ev) => {
                const moveX = ev.clientX;
                const moveY = ev.clientY;
                pageSlicePos.x = x + (moveX - downX);
                pageSlicePos.y = y + (moveY - downY);
                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>
 作者:__SomeBody https://www.bilibili.com/read/cv23969984 出处:bilibili

相关文章

  • android随笔之自定义View的Canvas用法

    对Canvas进行操作: 1,Canvas平移 2,Canvas缩放 3,Canvas旋转 Canvas操作例子 ...

  • View绘制画布的操作

    一、canvas的几何变换 对canvas进行平移、旋转、缩放、倾斜、裁减后,canvas将不会主动恢复原状,后续...

  • 常见术语

    scale 比例 缩放vertical 垂直vector 向量impact 影响spin 快速旋转gallery ...

  • CSS3 transform 元素的变形效果

    transform过渡效果配置 一.元素旋转 元素旋转后还是占用它原有位置,只不过旋转后的部分溢出了 二.元素缩放...

  • 三维空间的刚体运动

    旋转矩阵 对于同一个向量a(向量并没有随着坐标系的旋转而发生运动) 旋转向量与欧拉角 旋转矩阵R有九个元素,但仅有...

  • Canvas的变换

    Canvas的变换的相关内容主要是从平移(translate)、旋转(rotate)、缩放(scale)、矩阵变换...

  • webgl 24.为旋转平移后的正方体添加光照

    接上节的例子,我们对正方体做一些模型变换(旋转、平移、缩放)后再添加光照。 物体旋转、平移或缩放后法向量会发生变化...

  • Canvas学习笔记之变形

    Canvas 学习笔记之变形 -- by Damon 状态保存和恢复 状态包括: 当前的移动、旋转、缩放 stro...

  • OpenCV学习笔记(一)——旋转向量与旋转矩阵相互转化

    处理三维旋转问题时,通常采用旋转矩阵的方式来描述。一个向量乘以旋转矩阵等价于向量以某种方式进行旋转。除了采用旋转矩...

  • Android Matrix矩阵

    首先讲讲canvas里面的旋转、缩放、平移、 Android中可以通过Matrix和ColorMatrix对图像进...

网友评论

      本文标题:canvas 元素的缩放旋转-向量方式

      本文链接:https://www.haomeiwen.com/subject/dhunedtx.html