user1513388
user1513388

Reputation: 7451

Creating multiple repeating shapes

I have the following code which creates me rectangle that contains some text. I need to create multiple addressable instances of this rectangle so that I can individually animate them. Each rectangle needs to contain a different text label.

var s = Snap(800, 600);
var block = s.rect(50, 50, 100, 100, 5, 5);

block.attr({
    fill: "rgb(236, 240, 241)",
    stroke: "#1f2c39",
    strokeWidth: 3
});

var text = s.text(70, 105, "Hello World");
text.attr({
    'font-size':20
});

block.attr({
    width: (text.node.clientWidth + 50)
});

Rather than repeating my code I would like to create a function that accepts the text and the coordinates for placing the rectangle. What is the best way to achieve this ? Is this capability already included within snap.svg ?

UPDATE

I created another plugin, this time to import and scale SVG images. Is this the best approach to take for this ? Is the only way to scale the image using the `transform attribute ?

Import SVG plugin example.

Snap.plugin( function( Snap, Element, Paper, global ) {
    Paper.prototype.importImage = function( x, y, scale ) {
        var ig1 = s.group();
        var image = Snap.load("../package.svg", function ( loadedFragment ) {
            ig1.attr({transform: 'translate(' + x + ',' + y + ') scale('+ scale +')'});
            ig1.append( loadedFragment);
        } );
        return ig1;
    }
});

Upvotes: 0

Views: 61

Answers (1)

Ian
Ian

Reputation: 13852

You could create a plugin to give you a new element option that does it for you, for example...

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

  Paper.prototype.textRect = function( text, x, y ) {
        var block = s.rect(x, y, 100, 100, 5, 5)
                     .attr({
                        fill: "rgb(236, 240, 241)",
                        stroke: "#1f2c39",
                        strokeWidth: 3,
                      });

        var text = s.text(x + 20, y + 50, text).attr({ 'font-size': 20 });

        block.attr({ width: (text.node.clientWidth + 50)  });
  }         

});

var s = Snap(800,800)

s.textRect('Hi', 100, 100 ); 
s.textRect('There', 100, 200 );

example fiddle

You may want to put them both in a 'g' group element if you will move them around or drag them or something, so you can perform operations on the group.

Upvotes: 1

Related Questions