Question

Please could someone suggest how I can transform a loaded rectangle into a mask for an image? I want to be able to create rectangles my svg in illustrator - so the size and position is setup prior to loading the svg

I think this could work in the following steps.

Step1: Add jpeg image to svg Step2: Group rect and jpeg Step3: Turn rect into mask/clipping mask

Thanks David

Was it helpful?

Solution

The code that you look for is element.attr({mask:maskelement});.

In this case, element is the image element, referable e.g. by its id in the page. As is maskelement the element that would be your rectangle. Keep in mind that the color of the rectangle has influence on the transparency of the masked part, white making it 0% transparent, black making it 100% transparent.

As a simple example:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Snap test</title>
    <script src="snap/snap.svg.js"></script>
    <script>
        window.onload = function () {
            var s = Snap(800, 600);

            Snap.load("myexample.svg", function (f) {
                var element = f.select("#myimage");
                var maskelement = f.select("#mymask");
                element.attr({mask:maskelement});

                g = f.select("svg");
                s.append(g);
            });
        };
    </script>
</head>
</html>

Keep in mind that the SVG in this case contains the PNG and the masking rectangle. The PNG must have the id that you use in your code, as does the masking rectangle.

Edit: here you see the previous PNG: iPNG image "foo.png"

And the SVG sourcecode can be found here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top