Randomizing SVG Shapes

Go to Source

SVG shapes are all built from numbers. Obvious, perhaps, but also, I’m not sure we take as much advantage of that as we could with inline <svg>. For example, it’s pretty easy to generate a new pseudo-random number in JavaScript:

function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1) + min);
}

Now imagine a bunch of variables set to random numbers, and using ES6 template literals to stitch them together:

let newPoints = `${x1},${y1} {x2},${y2} {x3},${y3} {x3},${y3}`; 

Which makes a valid syntax for the points attribute of a <polygon>.

let polygon = document.querySelector("polygon");
polygon.setAttribute("points", newPoints);

A more detailed example of that, and a demo, over on the Media Temple blog.

Direct Link to ArticlePermalink


Randomizing SVG Shapes is a post from CSS-Tricks

Go to Source