Skip to content

Instantly share code, notes, and snippets.

@jonsadka
Last active February 8, 2017 18:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonsadka/8cc5d8de353686e6a4c1aeb2a551913e to your computer and use it in GitHub Desktop.
Save jonsadka/8cc5d8de353686e6a4c1aeb2a551913e to your computer and use it in GitHub Desktop.
Generative art with dashes
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; }
path {
animation: dash 2s linear infinite;
}
@keyframes dash {
to {
stroke-dashoffset: -16;
}
}
</style>
</head>
<body>
<script>
// Feel free to change or delete any of the code you see in this editor!
var width = 960;
var height = 500;
var svg = d3.select('body').append('svg')
.attr('width', width)
.attr('height', height)
var currentPath = 'M100,100 200,100';
var pos = {x: 200, y: 100};
var dash = {fill: 40, space: 10};
var direction = getNewDirection();
var boundary = {
top: 0, bottom: height, left: 0, right: width
}
svg.append('path')
.attr('class', 'special--line')
.attr('d', currentPath)
.attr('stroke', '#13939A')
.attr('fill', 'none')
.attr('stroke-width', 1)
function updateLine(){
direction = getNewDirection(direction);
pos = getNewLocation(pos, direction);
currentPath = `${currentPath} ${pos.x},${pos.y}`;
dash.fill += 5
dash.space += 1
d3.select('.special--line')
.transition()
.attr('stroke-dasharray', `${dash.fill} ${dash.space}`)
.attr('d', currentPath);
}
function getNewDirection(current) {
if (current === 'right') return 'down';
if (current === 'down') return 'left';
if (current === 'left') return 'up';
return 'right';
}
function getNewLocation(location, direction) {
const movedDistance = Math.round(Math.random()*200);
if (direction === 'right'){
location.x += movedDistance;
location.x = Math.min(location.x, boundary.right);
} else if (direction === 'down') {
location.y -= movedDistance;
location.y = Math.max(location.y, boundary.top);
} else if (direction === 'left') {
location.x -= movedDistance;
location.x = Math.max(location.x, boundary.left);
} else {
location.y += movedDistance;
location.y = Math.min(location.y, boundary.bottom);
}
return location;
}
setInterval(updateLine, 60)
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment