Resize Rectangle HTML5 Canvas

后端 未结 2 1741
终归单人心
终归单人心 2021-01-31 22:27

I have some functions to draw rectangles on a canvas element. When the element is drawn, I want to be able to resize it by dragging its corners.

2条回答
  •  北恋
    北恋 (楼主)
    2021-01-31 23:05

    Do a handle system: when the mouse move, get the distance to each corner to get the first one that is near the cursor then save it and resize your rectangle according to it.

    Here is a JSfiddle illustrating it: http://jsfiddle.net/BaliBalo/9HXMG/

    function getHandle(mouse) {
        if (dist(mouse, point(rect.x, rect.y)) <= handlesSize) return 'topleft';
        if (dist(mouse, point(rect.x + rect.w, rect.y)) <= handlesSize) return 'topright';
        if (dist(mouse, point(rect.x, rect.y + rect.h)) <= handlesSize) return 'bottomleft';
        if (dist(mouse, point(rect.x + rect.w, rect.y + rect.h)) <= handlesSize) return 'bottomright';
        if (dist(mouse, point(rect.x + rect.w / 2, rect.y)) <= handlesSize) return 'top';
        if (dist(mouse, point(rect.x, rect.y + rect.h / 2)) <= handlesSize) return 'left';
        if (dist(mouse, point(rect.x + rect.w / 2, rect.y + rect.h)) <= handlesSize) return 'bottom';
        if (dist(mouse, point(rect.x + rect.w, rect.y + rect.h / 2)) <= handlesSize) return 'right';
        return false;
    }
    

提交回复
热议问题