circledrawer.js 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. /*jslint browser: true */
  2. var CircleDrawer = function (canvasId, undoManager) {
  3. "use strict";
  4. var CANVAS_WIDTH = document.getElementById(canvasId).width,
  5. CANVAS_HEIGHT = document.getElementById(canvasId).height,
  6. MIN_CIRCLE_RADIUS = 10,
  7. MAX_CIRCLE_RADIUS = 40,
  8. drawingContext,
  9. circles = [],
  10. circleId = 0,
  11. drawingCanvas = window.document.getElementById(canvasId);
  12. if (drawingCanvas.getContext === undefined) {
  13. return;
  14. }
  15. drawingContext = drawingCanvas.getContext('2d');
  16. function clear() {
  17. drawingContext.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
  18. }
  19. function drawCircle(x, y, radius, color) {
  20. drawingContext.fillStyle = color;
  21. drawingContext.beginPath();
  22. drawingContext.arc(x, y, radius, 0, Math.PI * 2, true);
  23. drawingContext.closePath();
  24. drawingContext.fill();
  25. }
  26. function draw() {
  27. clear();
  28. var i,
  29. circle;
  30. for (i = 0; i < circles.length; i = i + 1) {
  31. circle = circles[i];
  32. drawCircle(circle.x, circle.y, circle.radius, circle.color);
  33. }
  34. }
  35. function removeCircle(id) {
  36. var i = 0, index = -1;
  37. for (i = 0; i < circles.length; i += 1) {
  38. if (circles[i].id === id) {
  39. index = i;
  40. }
  41. }
  42. if (index !== -1) {
  43. circles.splice(index, 1);
  44. }
  45. draw();
  46. }
  47. function createCircle(attrs) {
  48. circles.push(attrs);
  49. draw();
  50. undoManager.add({
  51. undo: function () {
  52. removeCircle(attrs.id);
  53. },
  54. redo: function () {
  55. createCircle(attrs);
  56. }
  57. });
  58. }
  59. drawingCanvas.addEventListener("click", function (e) {
  60. var mouseX = 0,
  61. mouseY = 0,
  62. intColor,
  63. hexColor,
  64. color,
  65. id = circleId,
  66. radius;
  67. if (!e) {
  68. e = window.event;
  69. }
  70. if (e.pageX || e.pageY) {
  71. mouseX = e.pageX;
  72. mouseY = e.pageY;
  73. } else if (e.clientX || e.clientY) {
  74. mouseX = e.clientX + document.body.scrollLeft
  75. + document.documentElement.scrollLeft;
  76. mouseY = e.clientY + document.body.scrollTop
  77. + document.documentElement.scrollTop;
  78. }
  79. mouseX -= drawingCanvas.offsetLeft;
  80. mouseY -= drawingCanvas.offsetTop;
  81. intColor = Math.floor(Math.random() * (256 * 256 * 256));
  82. hexColor = parseInt(intColor, 10).toString(16);
  83. color = '#' + ((hexColor.length < 2) ? "0" + hexColor : hexColor);
  84. id = id + 1;
  85. radius = MIN_CIRCLE_RADIUS + Math.random() * (MAX_CIRCLE_RADIUS - MIN_CIRCLE_RADIUS);
  86. createCircle({
  87. id: id,
  88. x: mouseX,
  89. y: mouseY,
  90. radius: radius,
  91. color: color
  92. });
  93. }, false);
  94. };