Search code examples
javascripthtmlcanvasdrawing

Is there a preferred way for creating a draw feature in a browser?


I want to be able to draw circles on picture at a mouseclick or touch on a display. I also want to remove given circles if they're clicked/touched again. I know how to check if a given coordinate is within a circle. The problem is that I don't know the best approach to this task. Atm I'm using HTML5 canvas to draw circles with the .stroke() function, but I don't know how to "store" these circles so I can remove them if the'yre clicked/touched again. Is there a better solution than canvas available, or am I even approaching the problem the right way?


Solution

  • This is a solution based on SVG instead of canvas. There is a benefit you might consider: it is easy to store and retrieve, as it is self-describing.

    makeSVG = (tag, attrs) => {
        let el = document.createElementNS('http://www.w3.org/2000/svg', tag);
        for (var k in attrs) el.setAttribute(k, attrs[k]);
        return el;
    }
    
    $(() => { 
      let $svg = $('svg')
      
      $('svg image').on('click', e => {
        let x = e.pageX - $svg.offset().left;
        let y = e.pageY - $svg.offset().top;
        
        var circle= makeSVG('circle', {cx: x, cy: y, r:40, stroke: 'black', 'stroke-width': 2, fill: 'red'});
        
        $svg.append(circle);
      })
      
      $('svg').on('click', 'circle', e => {
        $(e.currentTarget).remove()
      })
    })
    html, body {
      padding:0;
      margin:0;
      height:100%;
      width:100%;
      position: relative;
    }
    
    svg {
      height:100%;
      width:100%;
      border: 1px solid red;
      position: absolute;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
      <image xlink:href="https://mdn.mozillademos.org/files/6457/mdn_logo_only_color.png" height="100%" width="100%"/>
    </svg>