Adam Piper
Adam Piper

Reputation: 555

Creating svg elements which can be resized by dragging from the corner

I am creating a website with a team of people which allows the user to draw different types of charts. I am developing the Work Breakdown Tree (WBT) chart at the moment and having trouble with the svg elements.

I would like to be able to allow the user to resize the elements on the canvas by dragging the shape from the corner.

I have searched around the web for hours looking for a suitable solution but can't seem to find anything.

Could anyone be of any help to me please?

Thanks

Upvotes: 0

Views: 1334

Answers (1)

RashFlash
RashFlash

Reputation: 1002

ok here is the code i came up with, its not the best but it will help you understand how we can do "Resize"

Jsfiddle is here http://jsfiddle.net/sv66bxee/

My html code is:-

 <div style="border: 2px solid;width: 800px;">
        <svg id="mycanvas" width="800px" height="500px" version="1.1"  xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" >
        <rect id="myrect" fill="black" x="100" y="70" width="100" height="100" />

        <rect id="resize" fill="red" x="190" y="160" width="20" height="20" />
        </svg>
    </div>

and some Javascript:-

document.addEventListener('mousedown', mousedown, false);

        var mousedown_points;
        function mousedown(e) {

            var target = e.target;
            if (target.id === 'resize') {
                mousedown_points = {
                    x: e.clientX,
                    y: e.clientY
                }
                document.addEventListener('mouseup', mouseup, false);
                document.addEventListener('mousemove', mousemove, false);
            }
        }

        function mousemove(e) {
            var current_points = {
                x: e.clientX,
                y: e.clientY
            }

            var rect= document.getElementById('myrect');
            var w=parseFloat(rect.getAttribute('width'));
            var h=parseFloat(rect.getAttribute('height'));

            var dx=current_points.x-mousedown_points.x;
            var dy=current_points.y-mousedown_points.y;

            w+=dx;
            h+=dy;

            rect.setAttribute('width',w);
            rect.setAttribute('height',h);

            mousedown_points=current_points;

            updateResizeIcon(dx,dy);
        }

        function updateResizeIcon(dx,dy){
            var resize= document.getElementById('resize');
            var x=parseFloat(resize.getAttribute('x'));
            var y=parseFloat(resize.getAttribute('y'));

            x+=dx;
            y+=dy;

            resize.setAttribute('x',x);
            resize.setAttribute('y',y);
        }


        function mouseup(e) {
            document.removeEventListener('mouseup', mouseup, false);
            document.removeEventListener('mousemove', mousemove, false);
        }

Upvotes: 1

Related Questions