What is wrong with this snap svg plugin?

2019-08-16 02:33发布

I have this code :

 el.replace(/[0-9]*\.[0-9]*/g, function(x){ return (+x).toFixed(2)  }) };

It works great on an individual svg path to trim its decimal places. Now I want to be able to trim all the paths from a paper(svg).To do that I am trying to make a snap svg plugin here:

Snap.plugin(function(Snap, Element, Paper, glob){

     Paper.prototype.trimPthDec = function(){

    this.paper.selectAll('path').forEach( function(el) { el.trim() } ) ;

      function  trim(){

     el.replace(/[0-9]*\.[0-9]*/g, function(x){ return (+x).toFixed(2)  }) };

        //return paper;

});

But it doesn't seem to work when I call it like:

// And use it like this to update the paper with new paths?!:
trimPthDec(); // I get this error: Uncaught ReferenceError: trimPthDec is not defined

Could anybody tell me why it is not working please?

1条回答
我只想做你的唯一
2楼-- · 2019-08-16 03:07

Few bits wrong with the plugin and the code...mainly its run on the paper, so you need to reference that paper correctly in the code, and call the function as a prototype, rather than a standalone func (so paper.func() rather than func() )

Snap.plugin(function(Snap, Element, Paper, glob){

     Paper.prototype.trim = function(){

         this.selectAll('path').forEach( function(el) { 
             el.attr('d') && el.attr({ 'd':  el.attr('d').replace(/[0-9]*\.[0-9]*/g, function(x){ return (+x).toFixed(2)  }) });

          });
       };
});

var s = Snap("#svg");

var block = s.path('M200.123345,43.2432');

s.trim();
alert(block.attr('d'));

jsfiddle

查看更多
登录 后发表回答