Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drawing a rectangle using click, mouse move, and click

People also ask

How do you draw a rectangle mouse in canvas?

Here's how to click-move-click to create a rectanglevar isDrawing=false; var startX; var startY; In your mousedown event handler: If this is the starting click, set the isDrawing flag and set the startX/Y. If this is the ending click, clear the isDrawing flage and draw the rectangle.

How do I make a rectangle in HTML?

To draw a rectangle, specify the x and y coordinates (upper-left corner) and the height and width of the rectangle. There are three rectangle methods : fillRect() strokeRect()


You were close. So, the question isn't really about the "canvas" element in HTML5, but a canvas that is really a div.

http://jsfiddle.net/d9BPz/546/

In order for me to see what your code was trying to accomplish, I had to tidy it up. What needed to happen was tracking of the square element.

We are doing one of two things everytime we click on the canvas. We are either creating a rectangle element, or finishing a rectangle element. So, when we're finished it makes sense to set 'element' (previously named 'd') to null. When creating an element, we have to assign the new DOM element to 'element'.

Everytime the mouse moves, we want to get the mouse position. If the element is in the process of creation (or "not null"), then we need to resize the element.

Then we wrap it all up in a function, and that's all there is to it:

function initDraw(canvas) {
    var mouse = {
        x: 0,
        y: 0,
        startX: 0,
        startY: 0
    };
    function setMousePosition(e) {
        var ev = e || window.event; //Moz || IE
        if (ev.pageX) { //Moz
            mouse.x = ev.pageX + window.pageXOffset;
            mouse.y = ev.pageY + window.pageYOffset;
        } else if (ev.clientX) { //IE
            mouse.x = ev.clientX + document.body.scrollLeft;
            mouse.y = ev.clientY + document.body.scrollTop;
        }
    };

    var element = null;    
    canvas.onmousemove = function (e) {
        setMousePosition(e);
        if (element !== null) {
            element.style.width = Math.abs(mouse.x - mouse.startX) + 'px';
            element.style.height = Math.abs(mouse.y - mouse.startY) + 'px';
            element.style.left = (mouse.x - mouse.startX < 0) ? mouse.x + 'px' : mouse.startX + 'px';
            element.style.top = (mouse.y - mouse.startY < 0) ? mouse.y + 'px' : mouse.startY + 'px';
        }
    }

    canvas.onclick = function (e) {
        if (element !== null) {
            element = null;
            canvas.style.cursor = "default";
            console.log("finsihed.");
        } else {
            console.log("begun.");
            mouse.startX = mouse.x;
            mouse.startY = mouse.y;
            element = document.createElement('div');
            element.className = 'rectangle'
            element.style.left = mouse.x + 'px';
            element.style.top = mouse.y + 'px';
            canvas.appendChild(element)
            canvas.style.cursor = "crosshair";
        }
    }
}

Usage: Pass the block-level element that you would like to make a rectangle canvas. Example:

<!doctype html>
<html>
<head>
    <style>
    #canvas {
        width:2000px;
        height:2000px;
        border: 10px solid transparent;
    }
    .rectangle {
        border: 1px solid #FF0000;
        position: absolute;
    }
    </style>
</head>
<body>
    <div id="canvas"></div>
    <script src="js/initDraw.js"></script>
    <script>
        initDraw(document.getElementById('canvas'));
    </script>
</body>
</html>

Here's how to click-move-click to create a rectangle

Create these variables:

var isDrawing=false;
var startX;
var startY;

In your mousedown event handler:

  • If this is the starting click, set the isDrawing flag and set the startX/Y.
  • If this is the ending click, clear the isDrawing flage and draw the rectangle.

You might also want to change the mouse cursor so the user knows they are drawing.

if(isDrawing){
    isDrawing=false;
    ctx.beginPath();
    ctx.rect(startX,startY,mouseX-startX,mouseY-startY);
    ctx.fill();
    canvas.style.cursor="default";
}else{
    isDrawing=true;
    startX=mouseX;
    startY=mouseY;
    canvas.style.cursor="crosshair";
}

Here is a Fiddle: http://jsfiddle.net/m1erickson/7uNfW/

Instead of click-move-click, how about using drag to create a rectangle?

Create these variables:

var mouseIsDown=false;
var startX;
var startY;

In your mousedown event handler, set the mouseIsDown flag and set the startX/Y.

Optionally, change the cursor so the user knows their dragging a rectangle.

      mouseIsDown=true;
      startX=mouseX;
      startY=mouseY;
      canvas.style.cursor="crosshair";

In your mouseup event handler, clear the mouseIsDown flag and draw the rect

If you changed the cursor, change it back.

      mouseIsDown=false;
      ctx.beginPath();
      ctx.rect(startX,startY,mouseX-startX,mouseY-startY);
      ctx.fill();
      canvas.style.cursor="default";

For those who encountered the scrolling problem, I've found a fix.
You need to get the offset (using window.pageYOffset) and reduce it from the mouse position in any of the recommended snippets given. You should take it off from the height as well.