Skip to content

Instantly share code, notes, and snippets.

@omarlopesino
Created February 23, 2018 21:17
Show Gist options
  • Save omarlopesino/6ac87974ba6e39de8a0b2ee730d0c05f to your computer and use it in GitHub Desktop.
Save omarlopesino/6ac87974ba6e39de8a0b2ee730d0c05f to your computer and use it in GitHub Desktop.
VUE JS: D3 - Move img around a path
<template>
<div>
<svg id="d3-container" width="2000" height="500">
<clipPath id="clipCircle">
<circle r="120" cx="170" cy="140"></circle>
</clipPath>
<g>
<image id="face" x="0" y="20" width="300" height="300" xlink:href="https://api.omarlopesino.me/sites/default/files/2018-02/me.jpeg" clip-path="url(#clipCircle)">
</image>
</g>
</svg>
</div>
</template>
<script>
import * as d3 from "d3";
export default {
data() {
return {
svg: null,
face: null,
path: null,
lineY: 5,
counter: 0,
direction: true,
}
},
watch: {
lineY(val) {
this.path.attr('d', this.lineFunction()(this.lineData()));
}
},
mounted: function () {
this.initialize();
this.buildPath();
requestAnimationFrame(this.moveFace);
},
methods: {
lineData() {
return [ { "x": 5, "y": this.lineY}, { "x": 800, "y": this.lineY}];
},
lineFunction() {
return d3.line()
.x(function(d) { return d.x; })
.y(function(d) { return d.y; })
.curve(d3.curveLinear);
},
buildPath() {
//This is the accessor function we talked about above
//The line SVG Path we draw
this.path = this.svg.append("path")
.attr("d", this.lineFunction()(this.lineData()))
.attr("stroke", "blue")
.attr("stroke-width", 2)
.attr("fill", "none");
},
moveFace() {
/* Check to see where the stars are journeys to determine
what direction they should be travelling in */
var counter = this.counter;
var direction = this.direction;
var pathNode = this.path.node();
if (counter >= 1) {
/* we've hit the end! */
direction = false;
}
else if (counter <= 0) {
direction = true;
}
this.direction = direction;
/* Based on the direction variable either increase or decrease the counter */
if (direction) {
counter += 0.01;
} else {
counter -= 0.01;
}
this.counter = counter;
var straightLength = parseInt(pathNode.getTotalLength());
/* Now the magic part. We are able to call .getPointAtLength on the tow paths to return
the coordinates at any point along their lengths. We then simply set the stars to be positioned
at these coordinates, incrementing along the lengths of the paths */
var coordinates = (pathNode.getPointAtLength(counter * straightLength).x -15) + "," + (pathNode.getPointAtLength(counter * straightLength).y -15);
var translate = "translate("+ coordinates + ")",
rotate = " rotate(45deg" + coordinates + ")";
this.face.attr("transform", translate);
/* Use requestAnimationFrame to recursively call moveStar() 60 times a second
to create the illusion of movement */
requestAnimationFrame(this.moveFace);
},
initialize() {
this.svg = d3.select('#d3-container');
this.face = this.svg.select('#face');
}
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment