Guest User

Untitled

a guest
Nov 21st, 2017
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.71 KB | None | 0 0
  1. // toggles the color of a hexagon and all of it's surrounding hexagons.
  2. function toggleHex(target, hex) {
  3. const firstColIdx = target.row % 2 ? 0 : -1;
  4. const secondColIdx = target.row % 2 ? 1 : 0;
  5. const isNeighbor =
  6. (hex.col === target.col && hex.row === target.row) || // target
  7. (hex.row === target.row - 1 && (hex.col === target.col + firstColIdx || hex.col === target.col + secondColIdx)) || // above row
  8. (hex.row === target.row && (hex.col === target.col - 1 || hex.col === target.col + 1)) || // same row
  9. (hex.row === target.row + 1 && (hex.col === target.col + firstColIdx || hex.col === target.col + secondColIdx)); // below row
  10. if (isNeighbor) {
  11. return { ...hex, active: !hex.active };
  12. }
  13.  
  14. return hex;
  15. }
  16.  
  17. export default class Hexagons extends Component {
  18. componentDidMount() {
  19. // add click event handler to hexagons
  20. this.hexGroup = d3.select(this.svg).append('g');
  21. this.hexGroup.selectAll('.hex')
  22. .data(this.state.hexData)
  23. .enter()
  24. .append('path')
  25. ...
  26. .on('click', d => {
  27. // I'm not a huge fan of D3's global event object,
  28. // but it's what we get :)
  29. d3.event.preventDefault();
  30. d3.event.stopPropagation();
  31. this.setState({
  32. hexData: this.state.hexData.map(hex => toggleHex(d, hex))
  33. });
  34. })
  35.  
  36. }
  37.  
  38. componentDidUpdate() {
  39. // animate hexagon color every time the component's state changes
  40. const selection = this.hexGroup.selectAll('.hex')
  41. .data(this.state.hexData)
  42. .selectAll('path')
  43. .transition()
  44. .duration(500)
  45. .attr('fill', d => (d.active ? 'rgb(255, 1, 175)' : 'rgb(60, 60, 60)'));
  46. }
  47.  
  48. render() {
  49. ...
  50. }
  51. }
Add Comment
Please, Sign In to add comment