svgdotjs / svg.draw.js

An extension of svg.js which allows to draw elements with mouse
MIT License
239 stars 57 forks source link

JS error when calling 'cancel', 'stop' or 'clean' on a polygon with no point #55

Open fterrani opened 4 years ago

fterrani commented 4 years ago

I encountered this problem while using svg.draw.js 2.0.3 in a project several months ago. I quickly checked the commits up to 2.0.4 but I think the problem might still exist, in lineable.js. I was showing different tools to the user allowing to draw polygons. Switching from one tool to another required to abort the started drawing operation, potentially when no point was drawn yet.

svg.draw.js allows to use these methods:

The problem is that if the polygon being drawn still has no point in the SVG.js model, calling polygon.draw('clean') (or stop or cancel) will trigger an error in lineable.js's clean method because it tries to empty/clear this.set, a property containing the circles drawn above points that doesn't exist if init wasn't called yet.

The same bug exists potentially in lineable.js's drawCircles method.

Due to time and project workflow constraints, I wrote the following code as a patch so that element.draw('cancel') and element.draw('drawCircles') behave properly for the following SVG.js elements: line, polyline, polygon. I'm providing it here as an indication to help with bugfixing (definitely not as a pull request, I unfortunately don't have time to write a decent one):

(function()
{
    var elements = ['line','polyline','polygon'];
    elements.forEach(function(elementName)
    {
        var methods = ['clean', 'drawCircles'];
        methods.forEach(function(methodName)
        {
            var originalFunc = SVG.Element.prototype.draw.plugins[elementName][methodName];
            SVG.Element.prototype.draw.plugins[elementName][methodName] = function()
            {
                if (this.set)
                    originalFunc.call(this, arguments);
            };
        });
    });
})();