Skip to content

Instantly share code, notes, and snippets.

@sprajagopal
Created January 3, 2018 20:20
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 sprajagopal/88baafd93dae96b90fe309840976becc to your computer and use it in GitHub Desktop.
Save sprajagopal/88baafd93dae96b90fe309840976becc to your computer and use it in GitHub Desktop.
/**
* this function
* initializes the events
* necessary for painting on svg
* @param fn is the function to callback on complete of paint stroke
*
* @return None
*/
export function init (fn) {
/* check if fn is defined
*/
if( typeof fn !== "function" ){
console.log("Fn not defined");
return 0;
}
/* status print */
console.log("attaching events to svg now...");
/* curve basis is selected here to display user input */
var line = d3.line().curve(d3.curveBasis);
/* svg element in the DOM is selected for the manipulation */
var svg = d3.select("#pnt").call(d3.drag()
.container(function() { return this; })
.subject(function() { var p = [d3.event.x, d3.event.y]; return [p, p]; })
.on("start", dragstarted)
.on("end", onDrawComplete)
);
console.log(svg);
/* clickx and clicky store the stroke for sending to server/shapedetect */
var clicks = [];
/* drag start trigger event */
function dragstarted() {
console.log("drag started");
var d = d3.event.subject,
active = svg.append("path").datum(d).attr('class', 'drawstroke')
.style('fill', 'none')
.style('stroke','rgba(0,0,0,1)')
.style('stroke-width','3px'),
x0 = d3.event.x,
y0 = d3.event.y;
d3.event.on("drag", function() {
var x1 = d3.event.x,
y1 = d3.event.y,
dx = x1 - x0,
dy = y1 - y0;
clicks.push([x1,y1]);
if (dx * dx + dy * dy > 100) d.push([x0 = x1, y0 = y1]);
else d[d.length - 1] = [x1, y1];
active.attr("d", line);
});
}
/* draw stop event, in main app, this set of points will be sent to the
* shape detect library\
*/
function onDrawComplete(){
console.log("drag complete");
/**
* call function on draw complete
*/
fn(clicks);
/* reset clicks array for next paint
*/
clicks = [];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment