如何在画布上让SVG透明?

4

我们如何实现这个目标?

我在函数中得到了SVG,如何使它在画布上方透明?目前我的所有功能都在画布上运行。但是我发现SVG可以执行添加和删除功能。我该怎么做?

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");
    }
}

你的问题不够清楚。也许你是在问SVG <image>是否支持透明的GIF或PNG格式?而且你对HTML5的<canvas>元素没有任何问题,对吗? - Phrogz
1个回答

4
假设你询问的是 SVG 中 <image> 元素中的透明度问题,我很高兴地告诉你它可以正常工作:
演示:http://jsfiddle.net/XBCEK/ 演示截图
<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>

如果您将该SVG嵌入到页面中,并搭配以下CSS:
body { background:url(http://phrogz.net/tmp/grid.gif) }
svg  { background:rgba(255,0,0,0.3) /*…*/ }

...然后您会看到:

  • SVG 的背景默认为透明。我们甚至可以提供低透明度的颜色背景,让页面(网格)的背景显示出来。
  • 8 位透明度 PNG(球)和 1 位透明度 GIF(手)的背景都允许 SVG/页面的背景正确地透过来。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接