cupcakekid cupcakekid -4 years ago 103
Javascript Question

Reusing SVG.js code for various SVG's

I'm getting to grips with SVG.js

I have a pattern effect that I've created and would like to use in a number of SVG's.

I can create it in one SVG with the following code...

$( document ).ready(function() {

var draw = SVG('geo').size(1200, 1700);

// 100 lines of js creating geometric pattern, effectively this...
var rect = draw.polygon(coordinates).fill('#fff').stroke({ width: 1, color:'#fff'}).opacity(0)


});

This creates an SVG with ID geo. But I'd like to use this code again to generate various SVG's, ideally with different options (colour etc).

SVG('geo') refers to a particular SVG, how do I make it so I can apply this to any SVG I want on the page?

Hope that made sense

Answer Source

You can define a function that does this repeatedly. Something like the following:

function create_svg(dom_id, width, height, coord) {
  var draw = SVG(dom_id).size(width, height);
  var rect = draw.polygon(coord)
                 .fill('#fff')
                 .stroke({
                   width: 1,
                   color: '#fff'
                 })
                 .opacity(0);
}

$(function() {
  create_svg('geo', 1200, 1700, coordinates);
  create_svg('geo2', 1000, 1500, other_coordinates);
)};

If you need to use the created SVGs further, later on in the code, you could make the create_svg function return the created SVG object to a variable in your document.ready function.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download