美文网首页
canvas 画布中以相对位置绘制元素

canvas 画布中以相对位置绘制元素

作者: littlesunn | 来源:发表于2023-06-09 21: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>
</body>

</html>
<script>
    class MyRect {

        constructor(x, y, width, height) {   // 相对坐标,指相对于pageSlicePos的坐标
            this.x = x;
            this.y = y;
            this.width = width;
            this.height = height;
        }

        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 = "#000";
            ctx.fill();
            ctx.restore();
        }

    }

    // 当前 canvas 的 0 0 坐标,我们设置 canvas 左上角顶点为 0 0,向右👉和向下👇是 X Y 轴正方向,0,0 为 pageSlicePos 初始值
    const pageSlicePos = {
        x: 0,
        y: 0,
    };
    var scale = 10; // 缩放比例
    const solidColor = '#999'; // 实线颜色
    const dashedColor = '#ccc'; // 虚线颜色
    const zeroColor = '#358bf3'; // 0 点坐标系颜色
    const myCanvas = document.querySelector('#myCanvas');
    const GRIDSIZE = 5;  // 一个正方形网格的宽高大小, 一个GRIDSIZE视为一个单位
    const ctx = myCanvas.getContext('2d');
    myCanvas.addEventListener("mousedown", mouseDown);
    myCanvas.addEventListener("mousewheel", mouseWheel);
    let features = [
        new MyRect(50, 50, 10, 10),
    ];
    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) {
        if (e.wheelDelta > 0) {
            if (scale < 10) {
                scale++;
            }
        } else {
            if (scale > 1) {
                scale--;
            }
        }
    }

    /**
     * 拖动 canvas 动态渲染,拖动时,动态设置 pageSlicePos 的值
     * @param e Event
     */
    function mouseDown(e) {
        const downX = e.clientX;
        const downY = e.clientY;
        const { x, y } = pageSlicePos;
        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;
            };
        }
        myCanvas.onmouseup = (en) => {
            myCanvas.onmousemove = null;
            myCanvas.onmouseup = null;
        };
    }

    function getPixelPos(block) { // 获取实际像素坐标
        return {
            x: pageSlicePos.x + (block.x / GRIDSIZE) * scale,  // block.x:起点x, block.x / GRIDSIZE 表示多少个单位长度, (block.x / GRIDSIZE) * scale 表示实际像素宽度;pageSlicePos.x + (block.x / GRIDSIZE) * scale 表示距原点x方向多少距离开始绘制
            y: pageSlicePos.y + (block.y / GRIDSIZE) * scale,  // 同上
        };
    }

    // function getRelativePos(block) { // 获取相对的坐标,同理反推
    //     return {
    //         x: ((block.x - pageSlicePos.x) / scale) * GRIDSIZE,
    //         y: ((block.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);
        var width = getPixelSize(block.width);
        var height = getPixelSize(block.height);
        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)
        })
    }

    drawLineGrid();

</script> 作者:__SomeBody https://www.bilibili.com/read/cv23969959 出处:bilibili

相关文章

网友评论

      本文标题:canvas 画布中以相对位置绘制元素

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