Luke Lee
Luke Lee

Reputation: 45

How can we make SVG transparent on Canvas?

how can we achieve this?

I got the SVG in the function, how can i make it transparent on top of canvas?? Currently i have all my functions working on the canvas. But I found out that SVG can do the add and remove function. How can I go about it?

function Add() {
    var id = Math.floor(Math.random()*101+1);
        x = Math.random() * 550;
        y = Math.random() * 250;
    if (document.getElementById('amount').value < 50){
        document.getElementById('amount').value++;
        svg = document.getElementById("main");


        // construct uniqueid for the images
        uniqueid = "frog" + document.getElementById('amount').value;

        //namespaces for SVG
        svgNS="http://www.w3.org/2000/svg";
        xlinkNS="http://www.w3.org/1999/xlink";

        // create a image element
        image = document.createElementNS(svgNS, 'image');

        // set id and other attributes
        image.setAttributeNS(null, "id", uniqueid);
        image.setAttributeNS(xlinkNS, "href","jef-frog.gif");
        image.setAttributeNS(null, "x", x);
        image.setAttributeNS(null, "y", y);
        image.setAttributeNS(null, "width", "50");
        image.setAttributeNS(null, "height", "50");

        // append to svg
        svg.appendChild(image);

    } else {
        alert("we got 50");
    }
}

Upvotes: 4

Views: 4475

Answers (1)

Phrogz
Phrogz

Reputation: 303450

Assuming you are asking about transparency in SVG <image> elements, I'm pleased to say that it works just fine:

Demo: http://jsfiddle.net/XBCEK/

Screenshot from demo

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xl="http://www.w3.org/1999/xlink">
  <image xl:href="http://phrogz.net/tmp/alphaball.png"
         x="20" y="30" width="128" height="128" />
  <image xl:href="http://phrogz.net/tmp/hand.gif"
         x="220" y="30" width="32" height="32" />
</svg>​

If you embed that SVG on a page along with the following CSS:

body { background:url(http://phrogz.net/tmp/grid.gif) }
svg  { background:rgba(255,0,0,0.3) /*…*/ }

…then you will see that:

  • The background of the SVG is transparent by default. We can even provide a low-opacity color background that lets the background of the page (the grid) show through.
  • The background of both 8-bit-transparency PNG (the ball) and 1-bit transparency GIF (the hand) allow the background of the SVG/page to shine through correctly. ​

Upvotes: 4

Related Questions