画布的坐标系与鼠标事件不对齐

时间:2018-06-02 12:45:00

标签: javascript html css canvas

什么?屏幕上有一个画布(使用90%vh跨越视口的vw),您可以拖动鼠标进行绘制画布上的矩形。

如何?抓住mousedown事件和商店坐标。然后捕获mouseup事件并存储坐标。根据两组坐标绘制矩形。

正确的行为?如果我没有在 CSS 中设置画布的宽度和高度,它就像魅力一样。

问题?但是如果我在CSS中设置了90vw和90vh,坐标就会被破坏,坐标的位置会偏离一些偏移量。我不知道如何获得这种抵消。



    let mouseIsDown = false;
    let startX;
    let startY;
    let endX;
    let endY;
    const image = new Image();
    const rectangles = [];
    
    window.onload = () => {
        canvas.width = window.innerWidth;
    
        canvas.height = window.innerHeight;
    
        const ctx = canvas.getContext('2d');
    
        window.onmousedown = function (e) {
            // Ignore Outside canvas clicks
            if (e.srcElement == canvas) {
                canvas.style.cursor = "crosshair";
                mouseIsDown = true;
                startX = e.pageX - canvas.offsetLeft;
                startY = e.pageY - canvas.offsetTop;
            }
        }
    
        window.onmouseup = function (e) {
            console.log(e);
            // Ignore Outside canvas clicks
            if (e.srcElement == canvas) {
    
                canvas.style.cursor = "default";
                mouseIsDown = false;
                endX = e.pageX - canvas.offsetLeft;
                endY = e.pageY - canvas.offsetTop;
                const rect = {
                    x: startX,
                    y: startY,
                    width: endX - startX,
                    height: endY - startY
                }
    
                drawRectangle(ctx, rect.x, rect.y, rect.width, rect.height);
    
                rectangles.push(rect);
            }
        }
    }
    
    function drawRectangle(ctx, x, y, width, height) {
        ctx.strokeStyle = 'red';
        ctx.rect(x, y, width, height);
        ctx.stroke();
    }

 .container {
        display: flex;
        align-items: center;
        justify-content: center;
    }
    #canvas {
        width: 90vw;
        height: 90vh;
    }

        <div class="container">
            <canvas id="canvas"></canvas>
        </div>
&#13;
&#13;
&#13;

0 个答案:

没有答案