使用JS循环访问SVG

时间:2017-11-08 20:56:47

标签: javascript css svg

所以我制作了一个小星星SVG,我试图使用那个星形而不是造型跨度来让一堆气泡漂浮到我的div顶部。我在试图弄清楚如何使用我的Javascript循环而不是使用SVG来制作我的气泡而不是跨度时遇到了麻烦。

"use strict";

// variables
var numBubbles = 60;
var minSize = 10;
var maxSize = 20;
var container = document.getElementById("container");

// get the size of a bubble
// Randomized between minSize and maxSize
function bubbleSize() {
  return Math.floor(Math.random() * (maxSize - minSize + 1)) + minSize;
}

// Get the location of a bubble.
// Between left=2% and left=98%.
function bubbleLocation() {
  return Math.floor(Math.random() * 96) + 2;
}

// Create a bubble using the
// previous two functions.
function createBubble() {
  var size = bubbleSize();
  var location = bubbleLocation();

  // create span
  var el = document.createElement("span");

  // style span
  el.setAttribute("style", "width: " + size + "px; height: " + size + "px; left: " + location + "%; box-shadow: " + "0px 0px 12px 2px #ff4e85;");

  // append span
  container.appendChild(el);

}

// Start adding bubbles.
(function startBubbles() {
  var i = 0;

  function addBubble() {
    if (i < numBubbles) {
      createBubble();
      i++;
    } else {
      clearInterval(inter);
    }
  }

  // Add a bubble every 500ms.
  // But we don't want too many bubbles...

  var inter = setInterval(addBubble, 300);

})();

https://codepen.io/smugfox/pen/KyNxLG

1 个答案:

答案 0 :(得分:0)

您可以使用createBubble()中的Node.cloneNode()克隆大量SVG ...

var el = svg.cloneNode(true);

..或者您可以继续使用<span>,并在CSS中将SVG设置为background-image

span {
    background-image: url("/path/to/star.svg");
    background-size: contain;
    background-position: center;
    background-repeat: no-repeat;
    ...

无论哪种方式,如果你想在你的星上留下阴影,你需要使用SVG文件中的<filter>来做到这一点。

更新了笔:https://codepen.io/Sphinxxxx/pen/YEpbwZ
使用克隆的SVG。将cloneSVGs更改为false以使用带有背景图片的跨度。