index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Jitter Line</title>
<link href='https://fonts.googleapis.com/css?family=Raleway' rel='stylesheet' type='text/css'>
<script type="text/javascript" src="datgui-min.js"></script>
<link rel="stylesheet" href="animatedMouseMove.css">
<script src="https://d3js.org/d3.v3.min.js" charset="utf-8"></script>
</head>
<body>
<p>Use your mouse to sketch a (jittery) line.</p>
<section id="box" class="main">
</section>
<script src="animatedMouseMove.js"></script>
</body>
</html>
animatedMouseMove.js
"use strict";
document.body.addEventListener('touchmove', function(event) {
event.preventDefault();
}, false);
var FizzyText = function() {
this.jitter = 12;
this.tailLength = 40;
this.tailColor = '#ffffff';
};
var iteratePerSecond = 30;
var period = 1000 / iteratePerSecond;
var text = new FizzyText();
var gui = new dat.GUI();
var controller = {jitter: gui.add(text, 'jitter', 0, 80)
.onChange(function(value) {
text.jitter = value;
}),
tailLength: gui.add(text, 'tailLength', 0 , 100)
.onChange(function(value) {
text.tailLength = Math.floor(value);
points.splice(0, (points.length - text.tailLength));
}),
color: gui.addColor(text, 'tailColor')
.onChange(function(value) {
svg.select("path").attr("stroke", value);
})
};
var margin = {
top: 20,
right: 0,
bottom: 0,
left: 0
},
width = 1400 - margin.left - margin.right,
height = 3000 - margin.bottom - margin.top;
var points = [];
var lineFunction = d3.svg.line()
.x(function(d) {
return d.x + text.jitter * (Math.random() - .5) - margin.left;
})
.y(function(d) {
return d.y + text.jitter * (Math.random() - .5) - margin.top;
})
.interpolate('basis');
var svg = d3.select('body')
.append('svg')
.attr('width', width + margin.left + margin.right)
.attr('height', height + margin.top + margin.bottom)
.on("mousemove", function() {
updateArray(d3.mouse(this));
})
.on("touchmove", function() {
updateArray(d3.mouse(this));
});
svg.append('path')
.attr("d", lineFunction(points))
.attr("stroke", text.tailColor)
.attr("class", "mainPath");
var paths = svg.select("path");
function jitter() {
paths.attr("d", lineFunction(points))
requestAnimationFrame(jitter);
}
jitter();
function updateArray(coord) {
if(points.length < text.tailLength - 1){
points.push({
x: coord[0],
y: coord[1]
});
} else {
points.push(points[0]);
points[points.length - 1].x = coord[0];
points[points.length - 1].y = coord[1];
points.shift()
}
};