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

后端 未结 3 678
失恋的感觉
失恋的感觉 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 01:00

    Here's a outline of how to drag-draw a rectangle on canvas:

    In mousedown:

    • save the starting mouse position
    • set a flag indicating the drag has begun

    In mousemove:

    • clear the canvas of the previous rectangle
    • calculate the rectangle width/height based on the starting vs current mouse position
    • draw a rectangle from the starting XY to the current mouse position

    In mouseup:

    • clear the dragging flag because the drag is over

    Here's example code and a Demo: http://jsfiddle.net/m1erickson/6E2yd/

    
    
    
     
    
    
    
    
    
    
    
        

    Drag the mouse to create a rectangle

    • clear the

提交回复
热议问题