Skip to content

Instantly share code, notes, and snippets.

@eesur
Last active August 29, 2015 13:58
Show Gist options
  • Save eesur/9976847 to your computer and use it in GitHub Desktop.
Save eesur/9976847 to your computer and use it in GitHub Desktop.
d3 | manipulating a single SVG shape

Manipulating a single SVG shape triggered via user input.

Also a good way to illustrate how SVG coordinate space works. Note you need to put the radius in to view the circle (otherwise it's at 0).


The cx and cy attributes define the x and y coordinates of the center of the circle. 

If cx and cy are omitted, the circle's center is set to (0,0)

The r attribute defines the radius of the circle

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Manipulate SVG shape via input</title>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/d3/3.4.2/d3.js"></script>
<style>
body {font-family: monospace; line-height: 160%; font-size: 18px; margin: 0;}
input {border: 1px dotted #ccc; background: white; font-family: monospace; padding: 10px 20px; font-size: 18px; margin: 20px 10px 20px 20px; color: red; width: 120px;}
input:focus { background-color:yellow; outline: none;}
form {display: block; position: fixed; left: 10px; top: 10px; background: transparent; ;}
</style>
</head>
<body>
<form name="myform" onSubmit="return handleClick()">
<input name="Submit" type="submit" value="trigger" />
<input type="text" id="myRadius" maxlength="3" placeholder="radius" />
<input type="text" id="myX" maxlength="3" placeholder="x value"/>
<input type="text" id="myY" maxlength="3" placeholder="y value"/>
</form>
<script>
// width and height
var w = 960;
var h = 500;
var mySVG = d3.select("body")
.append("svg:svg")
.attr("width", w)
.attr("height", h)
var circle = mySVG.append("circle")
.style("fill", "grey")
.attr("r", 100)
.attr("cx", w/2)
.attr("cy", h/2);
function handleClick(event){
console.log(document.getElementById("myRadius").value)
draw(document.getElementById("myRadius").value, document.getElementById("myX").value, document.getElementById("myY").value)
return false;
}
function draw(rad, x, y){
circle
.style("fill", "red")
.attr("r", rad)
.attr("cx", x)
.attr("cy", y)
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment