Advertisement
badunius

hexes (js + svg)

Jul 9th, 2019
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class hPoint {
  2.   constructor(x = 0, y = 0, z = 0) {
  3.     this.x = x
  4.     this.y = y
  5.     this.z = 0 - (x + y)
  6.   }
  7.  
  8.   dist({ x = 0, y = 0 }) {
  9.     const point = new hPoint(x, y)
  10.     return Math.max(
  11.       Math.abs(this.x - point.x),
  12.       Math.abs(this.y - point.y),
  13.       Math.abs(this.z - point.z),
  14.     )
  15.   }
  16. }
  17.  
  18. const PREC = 2
  19. const DB = document.body
  20. const ANG = Math.PI / 3
  21. const RAD = 32
  22. const XMat = {
  23.   x: RAD * Math.sqrt(3),
  24.   y: 0,
  25. }
  26. const YMat = {
  27.   x: (Math.cos(ANG) * Math.sqrt(3) * RAD),
  28.   y: (Math.sin(ANG) * Math.sqrt(3) * RAD),
  29. }
  30.  
  31. var FLD
  32.  
  33. const pts = (new Array(6))
  34.   .fill(0)
  35.   .map((e, i) => ({
  36.     y: (Math.cos(ANG * i) * RAD),
  37.     x: (Math.sin(ANG * i) * RAD),
  38.   }))
  39.  
  40. HTMLElement.prototype.cel = function(tag) {
  41.   const el = document.createElement(tag)
  42.   if (el) { this.appendChild(el) }
  43.   return el
  44. }
  45.  
  46. HTMLElement.prototype.cen = function(NS, tag) {
  47.   const el = document.createElementNS(NS, tag)
  48.   if (el) { this.appendChild(el) }
  49.   return el
  50. }
  51.  
  52. function hex(x, y) {
  53.   const el = document.createElementNS('http://www.w3.org/2000/svg', 'polygon')
  54.  
  55.   el.setAttribute(
  56.     'points',
  57.     pts.map(p => `${(p.x + x * XMat.x + y * YMat.x).toFixed(PREC) * 1} ${(p.y + x * XMat.y + y * YMat.y).toFixed(PREC) * 1}`).join(' ')
  58.   )
  59.   FLD.appendChild(el)
  60.  
  61.   return el
  62. }
  63.  
  64. function area(x, y, rad) {
  65.   const center = new hPoint(0, 0)
  66.   for (let col = -rad; col <= rad; col++) {
  67.     for (let row = -rad; row <= rad; row++) {
  68.       if (center.dist({x: col, y: row}) <= rad) {
  69.         hex(col + x, row + x)
  70.       }
  71.     }
  72.   }
  73. }
  74.  
  75. function rect(x, y, wt, ht) {
  76.   for (let row = 0; row < ht; row++) {
  77.     const off = (row / 2) << 0
  78.     for (let col = 0; col < wt; col++) {
  79.       hex(x + col - off, y + row)
  80.     }
  81.   }
  82. }
  83.  
  84. function drop() {
  85.   FLD.innerHTML = ''
  86. }
  87.  
  88. (() => {
  89.   FLD = DB.cen('http://www.w3.org/2000/svg', 'svg')
  90. })()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement