|
| 1 | +import { EditorHost } from '../editor-host.js'; |
| 2 | +import { Point } from '../math/point.js'; |
| 3 | +import { SVGNS } from '../constants.js'; |
| 4 | +import { Tool } from './tool.js'; |
| 5 | +import { InsertElementCommand } from '../commands/insert-element-command.js'; |
| 6 | +import { CarveMouseEvent } from '../carve-mouse-event.js'; |
| 7 | + |
| 8 | +/** A tool for drawing an ellipse. */ |
| 9 | +export class EllipseTool extends Tool { |
| 10 | + private isDrawing: boolean = false; |
| 11 | + private startPoint: Point; |
| 12 | + private endPoint: Point; |
| 13 | + private drawingElem: SVGEllipseElement; |
| 14 | + |
| 15 | + constructor(host: EditorHost) { |
| 16 | + super(host); |
| 17 | + } |
| 18 | + |
| 19 | + onMouseDown(evt: CarveMouseEvent) { |
| 20 | + this.isDrawing = true; |
| 21 | + this.startPoint = new Point(evt.carveX, evt.carveY); |
| 22 | + this.endPoint = new Point(evt.carveX, evt.carveY); |
| 23 | + |
| 24 | + const elem = document.createElementNS(SVGNS, 'ellipse'); |
| 25 | + elem.setAttribute('cx', `${evt.carveX}`); |
| 26 | + elem.setAttribute('cy', `${evt.carveY}`); |
| 27 | + elem.setAttribute('fill', 'green'); |
| 28 | + elem.setAttribute('stroke-width', '1'); |
| 29 | + elem.setAttribute('stroke', 'black'); |
| 30 | + |
| 31 | + this.drawingElem = elem; |
| 32 | + this.host.getOverlay().appendChild(elem); |
| 33 | + console.log(`EllipseTool: Started creating an ellipse`); |
| 34 | + } |
| 35 | + |
| 36 | + onMouseUp(evt: CarveMouseEvent) { |
| 37 | + if (this.isDrawing) { |
| 38 | + this.isDrawing = false; |
| 39 | + this.endPoint = new Point(evt.carveX, evt.carveY); |
| 40 | + |
| 41 | + // Do not create a rect if it would be zero width/height. |
| 42 | + if (this.startPoint.x !== this.endPoint.x && this.startPoint.y !== this.endPoint.y) { |
| 43 | + this.host.execute(new InsertElementCommand(this.drawingElem)); |
| 44 | + console.log(`EllipseTool: Created an ellipse`); |
| 45 | + } else { |
| 46 | + this.drawingElem.parentElement.removeChild(this.drawingElem); |
| 47 | + console.log(`EllipseTool: Abandoned creating an ellipse`); |
| 48 | + } |
| 49 | + |
| 50 | + this.host.getOverlay().innerHTML = ''; |
| 51 | + this.cleanUp(); |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + onMouseMove(evt: CarveMouseEvent) { |
| 56 | + if (this.isDrawing) { |
| 57 | + this.endPoint.x = evt.carveX; |
| 58 | + this.endPoint.y = evt.carveY; |
| 59 | + this.drawingElem.setAttribute('rx', `${Math.abs(this.endPoint.x - this.startPoint.x)}`); |
| 60 | + this.drawingElem.setAttribute('ry', `${Math.abs(this.endPoint.y - this.startPoint.y)}`); |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + private cleanUp() { |
| 65 | + this.isDrawing = false; |
| 66 | + this.startPoint = null; |
| 67 | + this.endPoint = null; |
| 68 | + this.drawingElem = null; |
| 69 | + } |
| 70 | +} |
0 commit comments