Inspired by the New York Times' You Draw It, which allows the user to trace a line with the mouse that immediately appears on the screen, with specific constraints. Mouse event technique from https://bl.ocks.org/mbostock/4198499.
Last active
July 24, 2019 01:36
-
-
Save anbnyc/a83ec925d25871db80e45e04c4233736 to your computer and use it in GitHub Desktop.
Recreate functionality from NYT's "You draw it"
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.5.0/d3.min.js"></script> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script> | |
<style> | |
.background{ | |
fill: #c7c7c7; | |
} | |
.band{ | |
fill: none; | |
fill-opacity: 0; | |
stroke-opacity: 1; | |
stroke: #555; | |
stroke-width: 2px; | |
stroke-dasharray: 10 10; | |
} | |
.yourpath{ | |
fill: none; | |
stroke: #008000; | |
stroke-width: 2px; | |
stroke-dasharray: 2 2; | |
} | |
</style> | |
</head> | |
<body> | |
<svg/> | |
</body> | |
<script src="./myscript.js"></script> | |
</html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const w = 300; | |
const h = 200; | |
const datalen = 10; | |
let svg = d3.select("svg") | |
.attr("width",w) | |
.attr("height",h); | |
let background = svg.append("rect") | |
.attr("class","background") | |
.attr("width",w) | |
.attr("height",h); | |
let bands = svg.append("g") | |
bands.selectAll("rect.band") | |
.data(_.range(datalen)) | |
.enter() | |
.append("rect") | |
.attr("height",h) | |
.attr("width",w/datalen) | |
.attr("class","band") | |
.attr("x",d=>d*w/datalen); | |
let line = d3.line() | |
.x(d=>d[0]) | |
.y(d=>d[1]); | |
let pathdata = {}; | |
let path = svg.append("path") | |
.attr("class","yourpath"); | |
background | |
.on("mousedown",()=>{ | |
background | |
.on("mousemove",function(d,i){ | |
position = Math.round(d3.event.offsetX/(w/datalen)); | |
pathdata[position] = [position*w/datalen,d3.mouse(this)[1]]; | |
path.datum(_.values(pathdata)).attr("d",line); | |
}) | |
.on("mouseup",()=>{ | |
background | |
.on("mousemove",null) | |
.on("mouseup",null); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, Your codes are very helpful to my research on timelines of suicidal ideation. I've tried several ways to store the data on the mouse movements. In the console, I could pull the local data by console.log(pathdata), but still struggling on storing all data. Do you happen to have more insights on it? thanks in advance!