Skip to content

Instantly share code, notes, and snippets.

@jonsadka
Last active March 19, 2017 19:11
Show Gist options
  • Save jonsadka/3e609aa065d76e25ef99ddc692c0bfac to your computer and use it in GitHub Desktop.
Save jonsadka/3e609aa065d76e25ef99ddc692c0bfac to your computer and use it in GitHub Desktop.
Generative Patterns
license: mit
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
.parent-container {
position: relative;
}
.pattern-container {
position: absolute;
width: 100%;
height: 500px;
}
.pattern {
fill: none;
stroke: #857979;
stroke-width: 1px;
}
</style>
</head>
<body>
<div class="parent-container">
<div class="pattern-container">
<svg width="100%" height="100%">
<defs>
<pattern id="Pattern" x="0" y="0" width="60" height="60" patternUnits="userSpaceOnUse">
<path class="pattern first" d="M0 30,40 60,50 60,60 30,50 0,40 0,0 30" />
<path class="pattern second" d="M60 30,20 60,10 60,0 30,10 0,20 0,60 30" />
</pattern>
</defs>
<rect fill="url(#Pattern)" width="100%" height="100%"/>
</svg>
</div>
</div>
</body>
<script>
setInterval(function(){
const leftPosition = Math.round(Math.random() * 60);
d3.selectAll('.pattern')
.transition().duration(600)
.attr('d', (d, i) => getPath(d, i, leftPosition))
}, 1200)
function getPath(d, index, leftPosition) {
const rightPosition = 60 - leftPosition;
const flatWidth = 10;
const firstPath = `M0 30,${rightPosition - flatWidth} 60,${rightPosition} 60,60 30,${rightPosition} 0,${rightPosition - flatWidth} 0,0 30`;
const secondPath = `M60 30,${leftPosition + flatWidth} 60,${leftPosition} 60,0 30,${leftPosition} 0,${leftPosition + flatWidth} 0,60 30`;
if (index === 0){
return firstPath;
} else {
return secondPath
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment