Francis Hemsher
Francis Hemsher

Reputation: 3498

Snap.svg setStops causing error

Below is an interactive example attempting to implement setStops to a radial gradient. When the 'setStops' button is clicked an error message occurs: "setStops is not a function"

Am I using this correctly?

<!DOCTYPE HTML>
<html>
<head>
<title>Snap.svg setStops</title>
<script type="text/javascript" src="http://svgDiscovery.com/_SNP/snap.svg-min.js"></script>
</head>
<body>
<svg id=mySVG width=400 height=200></svg>
<br><button onClick=stopsSet()>setStops</button>
<script>
    var SNPsvg = Snap("#mySVG");
    var radialGradient = SNPsvg.gradient("r(.5,.5,.5,.5)#000-#f00-#fff-green");
    var circle = SNPsvg.circle(200,100,50).attr({fill: radialGradient});

    //---button---
    function stopsSet()
    {
        radialGradient.setStops("#fff-#000-#f00-#fc0");
        circle.attr({fill: radialGradient});
    }
</script>
</body>
</html>

Upvotes: 2

Views: 88

Answers (2)

Robert Longson
Robert Longson

Reputation: 124179

Seems to be a bug in snap.svg. The code for linearGradient looks like this:

    function gradientLinear(defs, x1, y1, x2, y2) {
        var el = Snap._.make("linearGradient", defs);
        el.stops = Gstops;
        el.addStop = GaddStop;
        el.getBBox = GgetBBox;
        el.setStops = GsetStops;

but for radialGradients it's this:

    function gradientRadial(defs, cx, cy, r, fx, fy) {
        var el = Snap._.make("radialGradient", defs);
        el.stops = Gstops;
        el.addStop = GaddStop;
        el.getBBox = GgetBBox;
        if (cx != null) {

The code to add the setStops function is missing.

I've created a pull request in Snap.svg to fix this so hopefully one of the maintainers will merge it and include it in a subsequent release. In the meantime you could always make the same change to a local copy of Snap.

Upvotes: 1

Ian
Ian

Reputation: 13852

I think that's because setStops is only available for a linearGradient and not a radialGradient (not sure if that's by design or not).

If you try gradient("L(0, 0, 100, 100)#000-#f00:25-#fff") I think the error will go away. Naturally that's probably not what you want, but I'm just explaining why I think the error is there.

One thing you can always do with Snap if you get stuck, is use a bit of your own markup if it's not supported direct, and add it in. Eg Snap.parse('Some SVG Markup')

var svgMarkup = Snap.parse('<defs><radialGradient id="exampleGradient"><stop offset="10%" stop-color="gold"/><stop offset="95%" stop-color="green"/></radialGradient></defs>');

SNPsvg.append( svgMarkup );

var radialGradient = SNPsvg.select('#exampleGradient')

var circle = SNPsvg.circle(200,100,50).attr({fill: radialGradient});

Example jsfiddle

Upvotes: 1

Related Questions