Drawing a rectangle on Canvas

前端 未结 1 1641
悲哀的现实
悲哀的现实 2020-12-17 07:17

I am trying to create a simple canvas program where the user can consistently create new shapes. This one is just a basic rectangle creator (I am hoping to expand it more to

相关标签:
1条回答
  • 2020-12-17 07:51

    You need to modify a couple of things in the code: (edit: there are many issues with this code. I went through some of them inline here, but haven't tested. If you put it in a fiddle it's easier for us to check)..

    Fiddle

    When mouse down occur initialize both start and end points. Call a common draw function that is not dependent on the event itself:

    function mouseDown(eve) {
        mouseIsDown = 1;
        var pos = getMousePos(canvas, eve);
        startX = endX = pos.x;
        startY = endY = pos.y;
        drawSquare(); //update
    }
    

    At mouse up, only register if isMouseDown is true, else this function will handle all incoming up-events (as you have attatched it to document, which is correct - window could have been used too):

    function mouseUp(eve) {
        if (mouseIsDown !== 0) {
            mouseIsDown = 0;
            var pos = getMousePos(canvas, eve);
            endX = pos.x;
            endY = pos.y;
            drawSquare(); //update on mouse-up
        }
    }
    

    Only draw if mouseisdown is true:

    function mouseXY(eve) {
    
        if (mouseIsDown !== 0) {
            var pos = getMousePos(canvas, eve);
            endX = pos.x;
            endY = pos.y;
    
            drawSquare();
        }
    }
    

    In addition you will need to clear the previous area of the rectangle before drawing a new or else it won't show when you draw a bigger rectangle and then move the mouse back to draw a smaller one.

    For simplicity you can do:

    function drawSquare() {
        // creating a square
        var width = Math.abs(startX - endX);
        var height = Math.abs(startY - endY);
    
        context.clearRect(0, 0, context.width, context.height);
        //or use fillRect if you use a bg color
    
        context.beginPath();
        context.rect(startX, startY, width, height);
        context.fillStyle = "yellow";
        context.fill();
        context.lineWidth = 7;
        context.strokeStyle = 'black';
        context.stroke();
    }
    

    Use this for mouse position:

    function getMousePos(canvas, evt) {
        var rect = canvas.getBoundingClientRect();
        return {
            x: evt.clientX - rect.left,
            y: evt.clientY - rect.top
        };
    }
    
    0 讨论(0)
提交回复
热议问题