Syed Waqas Bukhary
Syed Waqas Bukhary

Reputation: 5340

Draw multiple Rectangles with svg.draw.js

The issue was already posted here, but I think was never addressed. I need to create a new rect each time I click "Create SVG Rect" button. Hence drawing multiple rectangles.

<!DOCTYPE html>
<html lang="en">
<head><style>#test_slide { width: 500px; height: 500px; cursor: crosshair;border: solid;}</style></head><body>
<div id="test_slide"></div>
<button id="create_svg_rect" >Create SVG Rect</button>

<!--SCRIPT FILES-->
<script src="https://code.jquery.com/jquery-3.3.1.min.js"  defer="defer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/svg.js/2.7.1/svg.min.js" type="text/javascript" defer="defer"></script>
<script src="https://svgjs.dev/svg.draw.js/demo/svg.draw.min.js" type="text/javascript" defer="defer"></script>
<script>
document.getElementById("create_svg_rect").onclick = function() {
    //SVG.on(document, 'DOMContentLoaded', function() {
        var drawing = new SVG('test_slide').size('100%', '100%');
        var rect = drawing.rect().attr('stroke-width',1).attr('fill','none');
        drawing.on('mousedown', function(e){
            rect.draw(e);
        }, false);

        drawing.on('mouseup', function(e){
            rect.draw('stop', e);
            console.log(rect.svg());
            return;
        }, false);
    //});
        
};
</script>
</body></html>

Upvotes: 1

Views: 1393

Answers (1)

Stranger in the Q
Stranger in the Q

Reputation: 3898

In your code you were creating a whole new drawing and listeners everytime you click on the button. Thats not what you want.

Instead, just create one drawing (<svg>) and attach the listeners to it.

A click on the button only has to create a new rectangle.

To be able to access the rect-var in the listeners we have to define it in the outer scope. On click, we create a new rect and save it. On mousedown we start drawing and on mouseup we finish.

Here is working snippet:

document.addEventListener('DOMContentLoaded',() => {

  let rect, drawing = new SVG('test_slide').size('100%', '100%');

  drawing.on('mousedown', function(e){
     rect && rect.draw(e);
  });

  drawing.on('mouseup', function(e){
    if (rect) {
      rect.draw('stop', e);
      console.log(rect.svg());
      rect = null;
    } 
  });

  document.getElementById("create_svg_rect").addEventListener('click', function() {
    rect = drawing.rect().attr('stroke-width',1).attr('fill','none');
  });

})
#test_slide { width: 500px; height: 160px; cursor: crosshair;border: solid;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/svg.js/2.7.1/svg.min.js" type="text/javascript"></script>
<script src="https://svgjs.dev/svg.draw.js/demo/svg.draw.min.js" type="text/javascript"></script>

<div id="test_slide"></div>
<button id="create_svg_rect" >Create SVG Rect</button>

Since your code didnt use any jquery I removed it from the snippet.

Upvotes: 3

Related Questions