Advertisement
Cedri

Hexfield jQuery

Apr 19th, 2019
222
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
jQuery 1.42 KB | None | 0 0
  1. /*global $, document*/
  2. $.fn.hexGridWidget = function (radius, columns, rows, cssClass) {
  3.     'use strict';
  4.     var createSVG = function (tag) {
  5.         return $(document.createElementNS('http://www.w3.org/2000/svg', tag || 'svg'));
  6.     };
  7.     return $(this).each(function () {
  8.         var element = $(this),
  9.                 hexClick = function () {
  10.                     var hex = $(this);
  11.                     element.trigger($.Event('hexclick', hex.data()));
  12.                 },
  13.                 height = 72.43,
  14.                 svgParent = createSVG('svg').attr('tabindex', 1).appendTo(element).css({
  15.                     width: (1.5 * columns  +  .5) * radius,
  16.                     height: (2 * rows  +  1) * height
  17.                 }),
  18.                 column, row, center,
  19.                 toPoint = function (dx, dy) {
  20.                     return Math.round(dx + center.x) + ',' + Math.round(dy + center.y);
  21.                 };
  22.         for (row = 0; row < rows; row++) {
  23.             for (column = 0; column < columns; column++) {
  24.                 center = {x:Math.round((1 + 1.5 * column) * radius), y: Math.round(height * (1 + row * 2 + (column % 2)))};
  25.                 createSVG('polygon').attr({
  26.                     points: [
  27.                         toPoint(-1 * radius / 2, -1 * height),
  28.                         toPoint(radius / 2, -1 * height),
  29.                         toPoint(radius, 0),
  30.                         toPoint(radius / 2, height),
  31.                         toPoint(-1 * radius / 2, height),
  32.                         toPoint(-1 * radius, 0)
  33.                     ].join(' '),
  34.                     'class':cssClass,
  35.                     tabindex:1
  36.                 })
  37.                 .appendTo(svgParent).data({center:center, row:row, column:column}).on('click', hexClick).attr({'hex-row': row, 'hex-column': column});
  38.             }
  39.         }
  40.     });
  41. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement