How to draw a rectangle on canvas like we do on paint?

后端 未结 3 691
失恋的感觉
失恋的感觉 2021-01-25 00:03

Say i want to draw a rectangle on canvas. I want to be able to get the co-ordinates from user\'s mouse. Ideal scenario is user clicks at a point and drags down to another end li

3条回答
  •  终归单人心
    2021-01-25 00:44

    Using this function you can get the mousecoordinates

      function getMousePos(canvas, evt) {
        var rect = canvas.getBoundingClientRect();
        return {
          x: evt.clientX - rect.left,
          y: evt.clientY - rect.top
        };
      }
    

    this function takes in the canvas object and the event. Now you just have to add an eventHandler on mousedown and mouseup and you can get both the locations.

    var canvas = document.getElementById('canvasId');
    var ctx = canvas.getContext('2d');
    
    var locA, locB;
    
    document.addEventListener('mousedown', function(e) {
         e.preventDefault();
         locA = getMousePos(canvas, e);
    });
    
    document.addEventListener('mouseup', function(e) {
         e.preventDefault();
         locB = getMousePos(canvas, e);
    
         ctx.fillStyle = '#000000';
         ctx.fillRect(locA.x, locA.y, (locB.x - locA.x), (locB.y - locA.y));
    });
    

    function source: http://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/

    There are still some problems surrounding canvas coordinates vs document coordinates, but I'm sure you'll be able to fix that.

提交回复
热议问题