Skip to content

Instantly share code, notes, and snippets.

@lukewilde
Last active October 17, 2016 14:50
Show Gist options
  • Save lukewilde/1e9d0402715cb9ecd73149f24da2c532 to your computer and use it in GitHub Desktop.
Save lukewilde/1e9d0402715cb9ecd73149f24da2c532 to your computer and use it in GitHub Desktop.
var svgLines = [];
/**
* Create and store all our svg lines, we store them so we only have to create
* them once. We'll move around the created SVG lines to match the image
* positions later.
*/
function createLines() {
// I've imagined these are the ID's of your images. You could use some other attribute.
var lineDescriptions = [
['a', 'b'],
['b', 'c'],
['a', 'c']
];
// Array.map is cool: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
svgLines = lineDescriptions.map(createSvgLine);
}
/**
* Takes two image ID's, we can use jQuery to find where these are, and use them
* to set the initial positions for our lines.
*/
function createSvgLine(lineDescription) {
var nodeA = getNodeProperties(lineDescription[0]);
var nodeB = getNodeProperties(lineDescription[1]);
// IDK how to make an SVG, it should be something like this but you'll need to find out.
var $line = $(document.createElement('svg'));
// set the coordinates to match image A & B:
$line.attr({
x1: nodeA.x,
y1: nodeA.y,
x2: nodeB.x,
y2: nodeB.y,
// I store a reference to the image's this line uses as a data attribute, we'll need it later.
start: lineDescription[0],
end: lineDescription[1]
});
// TODO: you'll have to set all the style options in here.
return $line;
}
/**
* Cheeky function to take an element ID and gets me an object which holds the
* the X & Y coordinate for it. Hopefully.
*/
function getNodeProperties(image) {
var imagePosition = $('#' + image).position();
return {
y: imagePosition.top,
x: imagePosition.left
};
}
$(function() {
// Create all our lines, once.
createLines();
requestAnimationFrame(function() {
// update line position every frame.
svgLines.forEach(function(svgLine) {
// Each SVG will reference it's start and end images:
var nodeA = getNodeProperties(svgLine.attr('start'));
var nodeB = getNodeProperties(svgLine.attr('end'));
// Use the start and end images to update the line attributes.
$line.attr({
x1: nodeA.x,
y1: nodeA.y,
x2: nodeB.x,
y2: nodeB.y
});
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment