not really known
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

61 lines
2.1 KiB

  1. function Board(boardState, lineColor, deadCellColor, aliveYoungCellColor, aliveOldCellColor, cellWidth, cellHeight, rowPadding, colPadding, canvas) {
  2. this.onClick = function (clickHandler) {
  3. var _this = this;
  4. canvas.addEventListener('click', function (e) {
  5. var x = e.clientX - canvas.getBoundingClientRect().left;
  6. var y = e.clientY - canvas.getBoundingClientRect().top;
  7. var cellX = Math.floor(x / (_this.cellWidth + 2));
  8. var cellY = Math.floor(y / (_this.cellHeight + 2));
  9. clickHandler(cellX, cellY);
  10. });
  11. };
  12. this.draw = function () {
  13. canvasWidth = (cellWidth + rowPadding) * 50 - 2;
  14. canvasHeight = (cellHeight + colPadding) * 30 - 2;
  15. canvas.width = canvasWidth;
  16. canvas.height = canvasHeight;
  17. canvas.style.background = lineColor;
  18. canvas.style.boxShadow = '5px 5px 25px 0px rgba(46, 61, 73, 0.2)';
  19. this.ctx = canvas.getContext('2d');
  20. this.cellWidth = cellWidth;
  21. this.cellHeight = cellHeight;
  22. this.update(boardState);
  23. };
  24. this.update = function (state) {
  25. var _this2 = this;
  26. var cellColorFromState = [deadCellColor, aliveOldCellColor, aliveYoungCellColor];
  27. state.forEach(function (row, rowIndex) {
  28. var y = (_this2.cellHeight + colPadding) * rowIndex;
  29. row.forEach(function (cell, cellIndex) {
  30. var x = (_this2.cellWidth + rowPadding) * cellIndex;
  31. _this2.ctx.fillStyle = cellColorFromState[cell];
  32. _this2.ctx.fillRect(x, y, _this2.cellWidth, _this2.cellHeight);
  33. });
  34. });
  35. };
  36. this.handleResize = function (windowWidth, state) {
  37. var scale = windowWidth / canvasWidth;
  38. if (scale < 1) {
  39. canvas.width = canvasWidth * (scale - 0.1);
  40. canvas.height = canvasHeight * (scale - 0.1);
  41. this.cellWidth = (canvas.width - 2 * 50) / 50;
  42. this.cellHeight = (canvas.height - 2 * 30) / 30;
  43. this.update(state);
  44. } else {
  45. canvas.width = canvasWidth;
  46. canvas.height = canvasHeight;
  47. this.cellWidth = cellWidth;
  48. this.cellHeight = cellHeight;
  49. this.update(state);
  50. }
  51. };
  52. }
  53. define(function () {
  54. return Board;
  55. });