Skip to content

Instantly share code, notes, and snippets.

@iosonosempreio
Last active August 2, 2018 17:23
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 iosonosempreio/0fd290e63eef4e2e709b318bdd2dfa52 to your computer and use it in GitHub Desktop.
Save iosonosempreio/0fd290e63eef4e2e709b318bdd2dfa52 to your computer and use it in GitHub Desktop.
d3.symbol() custom shapes

How to create custom symbols to use with d3.symbol().

As far as I understood, commands are theese.

Readapted from this fiddle.

<html>
<style>
line {
stroke: #dadada;
stroke-width: 1px;
}
path {
fill: none;
stroke: black;
stroke-width: 1px;
}
</style>
<body>
<script src="//d3js.org/d3.v5.min.js"></script>
<script src="script.js"></script>
</body>
</html>
let width = 960
let height = 500
let svg = d3.select('body').append('svg')
.attr('width', width)
.attr('height', height)
let g = svg.append('g')
.attr('transform', 'translate(' + width / 2 + ',' + height / 2 + ')')
g.append('line')
.attr('x1', 0)
.attr('y1', -height / 2)
.attr('x2', 0)
.attr('y2', height / 2)
g.append('line')
.attr('x1', -width / 2)
.attr('y1', 0)
.attr('x2', width / 2)
.attr('y2', 0)
.style('stroke', '#DADADA')
.style('stroke-width', 1)
var cross = {
draw: function(context, size) {
context.moveTo(-size / 2, -size / 2)
context.lineTo(size / 2, size / 2)
context.moveTo(size / 2, -size / 2)
context.lineTo(-size / 2, size / 2)
}
}
var diamond = {
draw: function(context, size) {
context.moveTo(0, -size / 2)
context.lineTo(size / 3, 0)
context.lineTo(0, size / 2)
context.lineTo(-size / 3, 0)
context.lineTo(0, -size / 2)
context.closePath();
}
}
let size = 50;
g.append("path")
.attr("d", d3.symbol().type(cross).size(size))
g.append("path")
.attr("d", d3.symbol().type(diamond).size(size*1.3))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment