Skip to content

Instantly share code, notes, and snippets.

@jonsadka jonsadka/.block
Last active Mar 19, 2017

Embed
What would you like to do?
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
You can’t perform that action at this time.