Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through an SVG using JS

So I have a small star SVG that I made, and I'm trying to use that star instead of styling a span to make a bunch of bubbles float up to the top of my div. I'm having trouble trying to figure out how to get my Javascript loop to instead use an SVG to make my bubbles, instead of the span.

"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

like image 321
CChung Avatar asked Mar 18 '26 08:03

CChung


1 Answers

You can either clone a lot of SVGs using Node.cloneNode() in createBubble()...

var el = svg.cloneNode(true);

..or you can keep using <span>s, and set the SVG as background-image in CSS:

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

Either way, if you want a drop-shadow on your star, you need to do that using a <filter> in the SVG file.

Updated pen: https://codepen.io/Sphinxxxx/pen/YEpbwZ
Uses cloned SVGs. Change cloneSVGs to false to use spans with background image.

like image 65
Sphinxxx Avatar answered Mar 20 '26 21:03

Sphinxxx