0

I'm implementing an Eraser for drawing on a React Native application. The drawings in the application were implemented using SVG.

Found this very helpful answer on how to go about it by using Masks.

However, after implementing that, an edge case that came up while implementing the above was when a Mask is added, a new drawing on that coordinate wouldn't display since the Mask is hiding it.

So, I came up with a solution of using layers. When adding the Mask with the eraser, I set the Id to a number which is increased when the User picks the Eraser.

And, when drawing a new Path, use the incremented number as the mask id.

Here's a sample of my code:

Array.from(Array(currentEraserMaskLayer).keys()).map((value, index) => {
  return (
    <Mask key={`eraser-mask-${index + 1}`} id={`Mask${index + 1}`} maskUnits="userSpaceOnUse">
      <Rect width="100%" height="100%" fill="white" />
      <G>
        {currentShapes.map((shape) => {
            return shape.points.map((point, index) => {
              return (
                <Circle key={index} cx={point.x} cy={point.y} r={30} fill="#000" stroke="#000" strokeWidth={0} />
              );
            });
        })}
      </G>
    </Mask>
  );
});

And, the drawings are implemented like this:

 <Path
        key={`shape-${shape.id}`}
        d={shape.d}
        stroke={shape.stroke}
        strokeWidth={4}
        mask={`url(#Mask${shape.eraserMaskLayer})`}
      />

And this works, new drawings aren't hidden by existing masks.

But, another edge case crops up, older drawings aren't hidden by new Eraser masks, since they're on different 'layers'. And, this is where I'm stuck.

I'll appreciate any idea on how to move forward with this, or if there's another way of implementing an Eraser using SVG.

Please let me know if I need to provide any more info.

Many thanks.

Edwards Moses
  • 13
  • 1
  • 4
  • You could save yourself a lot of headaches if you copy the SVG drawing into a canvas. Then you can keep erasing and drawing endlessly. – Kokodoko Oct 18 '21 at 23:01
  • @Kokodoko, appreciate you leaving a comment. I'll love to; implementing this would be much easier using a Canvas. But, there's no native implementation of Canvas on mobile. The only available options are implemented using webviews. – Edwards Moses Oct 19 '21 at 08:29
  • In that case the only workable option is to let the user directly delete paths/shapes of the SVG by clicking on them, instead of allowing erasing freely. The complicated option would be to somehow subtract the mask path from the underlying paths. Webview is too slow / not an option? – Kokodoko Oct 19 '21 at 12:58
  • Hi @Kokodoko, Thanks for your reply. Eventually went with deleting paths & shapes of the SVG on click. And yeah, Webview is pretty slow for our use-case, and sunken costs in SVG already. Appreciate your help. – Edwards Moses Oct 19 '21 at 18:59

0 Answers0