Skip to content

Instantly share code, notes, and snippets.

@enjalot
Last active December 19, 2017 01:35
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 enjalot/84b8912125aabf20c0c7f09543d8c6a2 to your computer and use it in GitHub Desktop.
Save enjalot/84b8912125aabf20c0c7f09543d8c6a2 to your computer and use it in GitHub Desktop.
Center a QuickDraw drawing
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; }
</style>
</head>
<body>
<script>
var width = 960;
var height = 500;
var scale = 1.25
var delay = 1600
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.style("border", "1px solid #111")
var line = d3.line()
.x(function(d) { return d.x })
.y(function(d) { return d.y })
.curve(d3.curveBasis)
d3.json("https://storage.googleapis.com/fun-data/quickdraw/complex-faces.json", function(err, faces) {
render(0)
function render(i) {
var drawing = faces[i]
var strokes = strokifyDrawing(drawing.drawing)
center(strokes)
var ps = svg.selectAll("path").data(strokes)
ps.exit().remove()
var psE = ps.enter().append("path")
ps = psE.merge(ps)
ps
.attr("d", line)
.style("fill", "none")
.style("stroke", "#111")
.style("stroke-width", 3)
.style("stroke-linecap", "round")
setTimeout(function() {
i++
console.log("i", i)
if(i >= faces.length) i = 0;
render(i)
}, delay)
}
})
function center(strokes) {
var minY = Infinity
var maxY = -Infinity
var minX = Infinity
var maxX = -Infinity
var centroidX = 0
var centroidY = 0
var count = 0
strokes.forEach(function(stroke) {
stroke.forEach(function(p) {
centroidX += p.x
centroidY += p.y
count++
})
})
centroidX /= count;
centroidY /= count;
strokes.forEach(function(stroke) {
stroke.forEach(function(p) {
p.x *= scale
p.y *= scale
p.x += width/2 - centroidX * scale
p.y += height/2 - centroidY * scale
if(p.y < minY) minY = p.y
if(p.y > maxY) maxY = p.y
if(p.x < minX) minX = p.x
if(p.x > maxX) maxX = p.x
})
})
var diffX = minX - (width - maxX)
var diffY = minY - (height - maxY)
strokes.forEach(function(stroke) {
stroke.forEach(function(p) {
p.x -= diffX/2
p.y -= diffY/2
})
})
}
function strokifyDrawing(drawing) {
var strokes = drawing.map(function(s) {
var points = []
s[0].forEach(function(x,i) {
points.push({x: x, y: s[1][i] })
})
return points;
})
return strokes
}
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment