/
still-image.component.ts
766 lines (656 loc) · 27.7 KB
/
still-image.component.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
import {
AfterViewInit,
Component,
ElementRef,
EventEmitter,
Inject,
Input,
OnChanges,
OnDestroy,
Output,
Renderer2,
SimpleChanges
} from '@angular/core';
import { MatDialog, MatDialogConfig } from '@angular/material/dialog';
import { MatIconRegistry } from '@angular/material/icon';
import { DomSanitizer } from '@angular/platform-browser';
import {
ApiResponseError,
Constants,
CreateColorValue,
CreateGeomValue,
CreateLinkValue,
CreateResource,
CreateTextValueAsString,
KnoraApiConnection,
Point2D,
ReadColorValue,
ReadFileValue,
ReadGeomValue,
ReadResource,
ReadStillImageFileValue,
RegionGeometry,
UpdateFileValue,
UpdateResource,
UpdateValue,
WriteValueResponse
} from '@dasch-swiss/dsp-js';
import * as OpenSeadragon from 'openseadragon';
import { mergeMap } from 'rxjs/operators';
import { DspApiConnectionToken } from 'src/app/main/declarations/dsp-api-tokens';
import { DialogComponent } from 'src/app/main/dialog/dialog.component';
import { ErrorHandlerService } from 'src/app/main/services/error-handler.service';
import { NotificationService } from 'src/app/main/services/notification.service';
import { DspCompoundPosition } from '../../dsp-resource';
import { EmitEvent, Events, UpdatedFileEventValue, ValueOperationEventService } from '../../services/value-operation-event.service';
import { FileRepresentation } from '../file-representation';
import { RepresentationService } from '../representation.service';
/**
* represents a region resource.
*/
export class Region {
/**
*
* @param regionResource a resource of type Region
*/
constructor(readonly regionResource: ReadResource) {
}
/**
* get all geometry information belonging to this region.
*
*/
getGeometries() {
return this.regionResource.properties[Constants.HasGeometry] as ReadGeomValue[];
}
}
/**
* represents a still image file value including its regions.
*/
export class StillImageRepresentation {
/**
*
* @param stillImageFileValue a [[ReadStillImageFileValue]] representing an image.
* @param regions the regions belonging to the image.
*/
constructor(readonly stillImageFileValue: ReadStillImageFileValue, readonly regions: Region[]) {
}
}
/**
* represents a geometry belonging to a specific region resource.
*/
export class GeometryForRegion {
/**
*
* @param geometry the geometrical information.
* @param region the region the geometry belongs to.
*/
constructor(readonly geometry: RegionGeometry, readonly region: ReadResource) {
}
}
/**
* collection of `SVGPolygonElement` for individual regions.
*/
interface PolygonsForRegion {
[key: string]: HTMLElement[];
}
@Component({
selector: 'app-still-image',
templateUrl: './still-image.component.html',
styleUrls: ['./still-image.component.scss']
})
export class StillImageComponent implements OnChanges, OnDestroy, AfterViewInit {
@Input() images: FileRepresentation[];
@Input() imageCaption?: string;
@Input() iiifUrl?: string;
@Input() resourceIri: string;
@Input() project: string;
@Input() activateRegion?: string; // highlight a region
@Input() compoundNavigation?: DspCompoundPosition;
@Input() currentTab: string;
@Input() parentResource: ReadResource;
@Output() goToPage = new EventEmitter<number>();
@Output() regionClicked = new EventEmitter<string>();
@Output() regionAdded = new EventEmitter<string>();
@Output() loaded = new EventEmitter<boolean>();
loading = true;
failedToLoad = false;
regionDrawMode = false; // stores whether viewer is currently drawing a region
private _regionDragInfo; // stores the information of the first click for drawing a region
private _viewer: OpenSeadragon.Viewer;
private _regions: PolygonsForRegion = {};
constructor(
@Inject(DspApiConnectionToken) private _dspApiConnection: KnoraApiConnection,
private _dialog: MatDialog,
private _domSanitizer: DomSanitizer,
private _elementRef: ElementRef,
private _errorHandler: ErrorHandlerService,
private _matIconRegistry: MatIconRegistry,
private _notification: NotificationService,
private _renderer: Renderer2,
private _rs: RepresentationService,
private _valueOperationEventService: ValueOperationEventService
) {
OpenSeadragon.setString('Tooltips.Home', '');
OpenSeadragon.setString('Tooltips.ZoomIn', '');
OpenSeadragon.setString('Tooltips.ZoomOut', '');
OpenSeadragon.setString('Tooltips.FullPage', '');
// own draw region icon; because it does not exist in the material icons
this._matIconRegistry.addSvgIcon(
'draw_region_icon',
this._domSanitizer.bypassSecurityTrustResourceUrl('/assets/images/draw-region-icon.svg')
);
}
/**
* calculates the surface of a rectangular region.
*
* @param geom the region's geometry.
* @returns the surface.
*/
static surfaceOfRectangularRegion(geom: RegionGeometry): number {
if (geom.type !== 'rectangle') {
// console.log('expected rectangular region, but ' + geom.type + ' given');
return 0;
}
const w = Math.max(geom.points[0].x, geom.points[1].x) - Math.min(geom.points[0].x, geom.points[1].x);
const h = Math.max(geom.points[0].y, geom.points[1].y) - Math.min(geom.points[0].y, geom.points[1].y);
return w * h;
}
ngOnChanges(changes: SimpleChanges) {
if (changes['images'] && changes['images'].isFirstChange()) {
this._setupViewer();
}
if (changes['images']) {
this._openImages();
this._unhighlightAllRegions();
// --> TODO: check if this is necessary or could be handled below
// (remove the 'else' before the 'if', so changes['activateRegion'] is always checked for)
}
if (this.currentTab === 'annotations') {
this.renderRegions();
}
if (this.activateRegion !== undefined) {
this._highlightRegion(this.activateRegion);
}
if (changes['activateRegion']) {
this._unhighlightAllRegions();
}
}
ngAfterViewInit() {
this.loaded.emit(true);
}
ngOnDestroy() {
if (this._viewer) {
this._viewer.destroy();
this._viewer = undefined;
}
}
/**
* renders all ReadStillImageFileValues to be found in [[this.images]].
* (Although this.images is a Angular Input property, the built-in change detection of Angular does not detect changes in complex objects or arrays, only reassignment of objects/arrays.
* Use this method if additional ReadStillImageFileValues were added to this.images after creation/assignment of the this.images array.)
*/
updateImages() {
if (!this._viewer) {
this._setupViewer();
}
this._openImages();
}
/**
* renders all regions to be found in [[this.images]].
* (Although this.images is a Angular Input property, the built-in change detection of Angular does not detect changes in complex objects or arrays, only reassignment of objects/arrays.
* Use this method if additional regions were added to the resources.images)
*/
updateRegions() {
if (!this._viewer) {
this._setupViewer();
}
this.renderRegions();
}
/**
* when the draw region button is clicked, this method is called from the html. It sets the draw mode to true and
* prevents navigation by mouse (so that the region can be accurately drawn).
*/
drawButtonClicked(): void {
this.regionDrawMode = !this.regionDrawMode;
this._viewer.setMouseNavEnabled(!this.regionDrawMode);
}
/**
* adds a ROI-overlay to the viewer for every region of every image in this.images
*/
renderRegions(): void {
/**
* sorts rectangular regions by surface, so all rectangular regions are clickable.
* Non-rectangular regions are ignored.
*
* @param geom1 first region.
* @param geom2 second region.
*/
const sortRectangularRegion = (geom1: GeometryForRegion, geom2: GeometryForRegion) => {
if (geom1.geometry.type === 'rectangle' && geom2.geometry.type === 'rectangle') {
const surf1 = StillImageComponent.surfaceOfRectangularRegion(geom1.geometry);
const surf2 = StillImageComponent.surfaceOfRectangularRegion(geom2.geometry);
// if reg1 is smaller than reg2, return 1
// reg1 then comes after reg2 and thus is rendered later
if (surf1 < surf2) {
return 1;
} else {
return -1;
}
} else {
return 0;
}
};
this.removeOverlays();
let imageXOffset = 0; // see documentation in this.openImages() for the usage of imageXOffset
for (const image of this.images) {
const stillImage = image.fileValue as ReadStillImageFileValue;
const aspectRatio = (stillImage.dimY / stillImage.dimX);
// collect all geometries belonging to this page
const geometries: GeometryForRegion[] = [];
image.annotations.map((reg) => {
this._regions[reg.regionResource.id] = [];
const geoms = reg.getGeometries();
geoms.map((geom) => {
const geomForReg = new GeometryForRegion(geom.geometry, reg.regionResource);
geometries.push(geomForReg);
});
});
// sort all geometries belonging to this page
geometries.sort(sortRectangularRegion);
// render all geometries for this page
for (const geom of geometries) {
const geometry = geom.geometry;
const colorValues: ReadColorValue[] = geom.region.properties[Constants.HasColor] as ReadColorValue[];
// if the geometry has a color property, use that value as the color for the line
if (colorValues && colorValues.length) {
geometry.lineColor = colorValues[0].color;
}
const commentValue = (geom.region.properties[Constants.HasComment] ? geom.region.properties[Constants.HasComment][0].strval : '');
if (!this.failedToLoad) {
this._createSVGOverlay(geom.region.id, geometry, aspectRatio, imageXOffset, geom.region.label, commentValue);
}
imageXOffset++;
}
}
}
/**
* removes SVG overlays from the DOM.
*/
removeOverlays() {
for (const reg in this._regions) {
if (this._regions.hasOwnProperty(reg)) {
for (const pol of this._regions[reg]) {
if (pol instanceof HTMLElement) {
pol.remove();
}
}
}
}
this._regions = {};
this._viewer.clearOverlays();
}
/**
* display message to confirm the copy of the citation link (ARK URL)
*/
openSnackBar(message: string) {
this._notification.openSnackBar(message);
}
openReplaceFileDialog() {
const propId = this.parentResource.properties[Constants.HasStillImageFileValue][0].id;
const dialogConfig: MatDialogConfig = {
width: '800px',
maxHeight: '80vh',
position: {
top: '112px'
},
data: { mode: 'replaceFile', title: '2D Image (Still Image)', subtitle: 'Update image of the resource', representation: 'stillImage', id: propId },
disableClose: true
};
const dialogRef = this._dialog.open(
DialogComponent,
dialogConfig
);
dialogRef.afterClosed().subscribe((data) => {
if (data) {
this._replaceFile(data);
}
});
}
openPage(p: number) {
this.regionDrawMode = false;
this.goToPage.emit(p);
}
private _replaceFile(file: UpdateFileValue) {
const updateRes = new UpdateResource();
updateRes.id = this.parentResource.id;
updateRes.type = this.parentResource.type;
updateRes.property = Constants.HasStillImageFileValue;
updateRes.value = file;
this._dspApiConnection.v2.values.updateValue(updateRes as UpdateResource<UpdateValue>).pipe(
mergeMap((res: WriteValueResponse) => this._dspApiConnection.v2.values.getValue(this.parentResource.id, res.uuid))
).subscribe(
(res2: ReadResource) => {
this._valueOperationEventService.emit(
new EmitEvent(Events.FileValueUpdated, new UpdatedFileEventValue(
res2.properties[Constants.HasStillImageFileValue][0])));
},
(error: ApiResponseError) => {
this._errorHandler.showMessage(error);
}
);
}
/**
* opens the dialog to enter further properties for the region after it has been drawn and calls the function to upload the region after confirmation
* @param startPoint the start point of the drawing
* @param endPoint the end point of the drawing
* @param imageSize the image size for calculations
*/
private _openRegionDialog(startPoint: Point2D, endPoint: Point2D, imageSize: Point2D, overlay: Element): void {
const dialogConfig: MatDialogConfig = {
width: '337px',
maxHeight: '80vh',
position: {
top: '112px'
},
data: { mode: 'addRegion', title: 'Create a region', subtitle: 'Add further properties', id: this.resourceIri },
disableClose: true
};
const dialogRef = this._dialog.open(
DialogComponent,
dialogConfig
);
dialogRef.afterClosed().subscribe((data) => {
// remove the drawn rectangle as either the cancel button was clicked or the region will be displayed
this._viewer.removeOverlay(overlay);
if (data) { // data is null if the cancel button was clicked
this._uploadRegion(startPoint, endPoint, imageSize, data.color, data.comment, data.label);
}
});
}
/**
* uploads the region after being prepared by the dialog
* @param startPoint the start point of the drawing
* @param endPoint the end point of the drawing
* @param imageSize the image size for calculations
* @param color the value for the color entered in the form
* @param comment the value for the comment entered in the form
* @param label the value for the label entered in the form
*/
private _uploadRegion(startPoint: Point2D, endPoint: Point2D, imageSize: Point2D, color: string, comment: string, label: string) {
const x1 = Math.max(Math.min(startPoint.x, imageSize.x), 0) / imageSize.x;
const x2 = Math.max(Math.min(endPoint.x, imageSize.x), 0) / imageSize.x;
const y1 = Math.max(Math.min(startPoint.y, imageSize.y), 0) / imageSize.y;
const y2 = Math.max(Math.min(endPoint.y, imageSize.y), 0) / imageSize.y;
const geomStr = '{"status":"active","lineColor":"' + color + '","lineWidth":2,"points":[{"x":' + x1.toString() +
',"y":' + y1.toString() + '},{"x":' + x2.toString() + ',"y":' + y2.toString() + '}],"type":"rectangle"}';
const createResource = new CreateResource();
createResource.label = label;
createResource.type = Constants.Region;
createResource.attachedToProject = this.project;
const geomVal = new CreateGeomValue();
geomVal.type = Constants.GeomValue;
geomVal.geometryString = geomStr;
const colorVal = new CreateColorValue();
colorVal.type = Constants.ColorValue;
colorVal.color = color;
const linkVal = new CreateLinkValue();
linkVal.type = Constants.LinkValue;
linkVal.linkedResourceIri = this.resourceIri;
const commentVal = new CreateTextValueAsString();
commentVal.type = Constants.TextValue;
commentVal.text = comment;
createResource.properties = {
[Constants.HasComment]: [commentVal],
[Constants.HasColor]: [colorVal],
[Constants.IsRegionOfValue]: [linkVal],
[Constants.HasGeometry]: [geomVal]
};
this._dspApiConnection.v2.res.createResource(createResource).subscribe(
(res: ReadResource) => {
this.regionAdded.emit(res.id);
},
(error) => {
this._errorHandler.showMessage(error);
}
);
}
/**
* set up function for the region drawer
*/
private _addRegionDrawer() {
new OpenSeadragon.MouseTracker({
element: this._viewer.canvas,
pressHandler: (event) => {
if (!this.regionDrawMode) {
return;
}
const overlayElement = this._renderer.createElement('div');
overlayElement.style.background = 'rgba(255,0,0,0.3)';
const viewportPos = this._viewer.viewport.pointFromPixel((event as OpenSeadragon.ViewerEvent).position);
this._viewer.addOverlay(overlayElement, new OpenSeadragon.Rect(viewportPos.x, viewportPos.y, 0, 0));
this._regionDragInfo = {
overlayElement: overlayElement,
startPos: viewportPos
};
},
dragHandler: (event) => {
if (!this._regionDragInfo) {
return;
}
const viewPortPos = this._viewer.viewport.pointFromPixel((event as OpenSeadragon.ViewerEvent).position);
const diffX = viewPortPos.x - this._regionDragInfo.startPos.x;
const diffY = viewPortPos.y - this._regionDragInfo.startPos.y;
const location = new OpenSeadragon.Rect(
Math.min(this._regionDragInfo.startPos.x, this._regionDragInfo.startPos.x + diffX),
Math.min(this._regionDragInfo.startPos.y, this._regionDragInfo.startPos.y + diffY),
Math.abs(diffX),
Math.abs(diffY)
);
this._viewer.updateOverlay(this._regionDragInfo.overlayElement, location);
this._regionDragInfo.endPos = viewPortPos;
},
releaseHandler: () => {
if (this.regionDrawMode) {
const imageSize = this._viewer.world.getItemAt(0).getContentSize();
const startPoint = this._viewer.viewport.viewportToImageCoordinates(this._regionDragInfo.startPos);
const endPoint = this._viewer.viewport.viewportToImageCoordinates(this._regionDragInfo.endPos);
this._openRegionDialog(startPoint, endPoint, imageSize, this._regionDragInfo.overlayElement);
this._regionDragInfo = null;
this.regionDrawMode = false;
this._viewer.setMouseNavEnabled(true);
}
}
});
}
/**
* highlights the polygon elements associated with the given region.
*
* @param regionIri the Iri of the region whose polygon elements should be highlighted..
*/
private _highlightRegion(regionIri) {
const activeRegion: HTMLElement[] = this._regions[regionIri];
if (activeRegion !== undefined) {
for (const pol of activeRegion) {
pol.setAttribute('class', 'region active');
}
}
}
/**
* unhighlights the polygon elements of all regions.
*
*/
private _unhighlightAllRegions() {
for (const reg in this._regions) {
if (this._regions.hasOwnProperty(reg)) {
for (const pol of this._regions[reg]) {
pol.setAttribute('class', 'region');
}
}
}
}
/**
* initializes the OpenSeadragon _viewer
*/
private _setupViewer(): void {
const viewerContainer = this._elementRef.nativeElement.getElementsByClassName('osd-container')[0];
const osdOptions = {
element: viewerContainer,
sequenceMode: false,
showReferenceStrip: true,
zoomInButton: 'DSP_OSD_ZOOM_IN',
zoomOutButton: 'DSP_OSD_ZOOM_OUT',
previousButton: 'DSP_OSD_PREV_PAGE',
nextButton: 'DSP_OSD_NEXT_PAGE',
homeButton: 'DSP_OSD_HOME',
fullPageButton: 'DSP_OSD_FULL_PAGE',
// rotateLeftButton: 'DSP_OSD_ROTATE_LEFT', // doesn't work yet
// rotateRightButton: 'DSP_OSD_ROTATE_RIGHT', // doesn't work yet
showNavigator: true,
navigatorPosition: 'ABSOLUTE' as const,
navigatorTop: 'calc(100% - 136px)',
navigatorLeft: 'calc(100% - 136px)',
navigatorHeight: '120px',
navigatorWidth: '120px',
gestureSettingsMouse: {
clickToZoom: false // do not zoom in on click
}
};
this._viewer = new OpenSeadragon.Viewer(osdOptions);
this._viewer.addHandler('full-screen', (args) => {
if (args.fullScreen) {
viewerContainer.classList.add('fullscreen');
} else {
viewerContainer.classList.remove('fullscreen');
}
});
this._addRegionDrawer();
}
/**
* adds all images in this.images to the _viewer.
* Images are positioned in a horizontal row next to each other.
*/
private _openImages(): void {
// imageXOffset controls the x coordinate of the left side of each image in the OpenSeadragon viewport coordinate system.
// the first image has its left side at x = 0, and all images are scaled to have a width of 1 in viewport coordinates.
// see also: https://openseadragon.github.io/examples/viewport-coordinates/
// reset the status
this.failedToLoad = false;
const fileValues: ReadFileValue[] = this.images.map(
img => img.fileValue
);
// display only the defined range of this.images
const tileSources: object[] = this._prepareTileSourcesFromFileValues(fileValues);
this.removeOverlays();
this._viewer.addOnceHandler('open', (args) => {
// check if the current image exists
if (this.iiifUrl.includes(args.source['@id'])) {
this.failedToLoad = !this._rs.doesFileExist(args.source['@id'] + '/info.json');
if (this.failedToLoad) {
// failed to laod
// disable mouse navigation incl. zoom
this._viewer.setMouseNavEnabled(false);
// disable the navigator
this._viewer.navigator.element.style.display = 'none';
// disable the region draw mode
this.regionDrawMode = false;
// stop loading tiles
this._viewer.removeAllHandlers('open');
} else {
// enable mouse navigation incl. zoom
this._viewer.setMouseNavEnabled(true);
// enable the navigator
this._viewer.navigator.element.style.display = 'block';
}
this.loading = false;
}
});
this._viewer.open(tileSources);
}
/**
* prepare tile sources from the given sequence of [[ReadFileValue]].
*
* @param imagesToDisplay the given file values to de displayed.
* @returns the tile sources to be passed to OSD _viewer.
*/
private _prepareTileSourcesFromFileValues(imagesToDisplay: ReadFileValue[]): object[] {
const images = imagesToDisplay as ReadStillImageFileValue[];
let imageXOffset = 0;
const imageYOffset = 0;
const tileSources = [];
// let i = 0;
for (const image of images) {
const sipiBasePath = image.iiifBaseUrl + '/' + image.filename;
const width = image.dimX;
const height = image.dimY;
// construct OpenSeadragon tileSources according to https://openseadragon.github.io/docs/OpenSeadragon.Viewer.html#open
tileSources.push({
// construct IIIF tileSource configuration according to https://iiif.io/api/image/3.0
tileSource: {
'@context': 'http://iiif.io/api/image/3/context.json',
'id': sipiBasePath,
height: height,
width: width,
profile: ['level2'],
protocol: 'http://iiif.io/api/image',
tiles: [{
scaleFactors: [1, 2, 4, 8, 16, 32],
width: 1024
}]
},
x: imageXOffset,
y: imageYOffset,
preload: true
});
imageXOffset++;
}
return tileSources;
}
/**
* creates and adds a ROI-overlay to the viewer
* @param regionIri the Iri of the region.
* @param geometry - the geometry describing the ROI
* @param aspectRatio - the aspectRatio (h/w) of the image on which the geometry should be placed
* @param xOffset - the x-offset in Openseadragon viewport coordinates of the image on which the geometry should be placed
* @param toolTip - the tooltip which should be displayed on mousehover of the svg element
*/
private _createSVGOverlay(regionIri: string, geometry: RegionGeometry, aspectRatio: number, xOffset: number, regionLabel: string, regionComment: string): void {
const lineColor = geometry.lineColor;
const lineWidth = geometry.lineWidth;
const regEle: HTMLElement = this._renderer.createElement('div');
regEle.id = 'region-overlay-' + Math.random() * 10000;
regEle.className = 'region';
regEle.setAttribute('style', 'outline: solid ' + lineColor + ' ' + lineWidth + 'px;');
const diffX = geometry.points[1].x - geometry.points[0].x;
const diffY = geometry.points[1].y - geometry.points[0].y;
const loc = new OpenSeadragon.Rect(
Math.min(geometry.points[0].x, geometry.points[0].x + diffX),
Math.min(geometry.points[0].y, geometry.points[0].y + diffY),
Math.abs(diffX),
Math.abs(diffY * aspectRatio));
loc.y = loc.y * aspectRatio;
this._viewer.addOverlay({
element: regEle,
location: loc,
});
// mouse tracker has to be activated on the open seadragon viewer
// solution from: https://github.com/openseadragon/openseadragon/issues/1419#issuecomment-371564878
const tracker = new OpenSeadragon.MouseTracker({
element: regEle,
clickHandler: function (event) { }
});
this._regions[regionIri].push(regEle);
const comEle: HTMLElement = this._renderer.createElement('div');
comEle.className = 'annotation-tooltip';
comEle.innerHTML = `<strong>${regionLabel}</strong><br>${regionComment}`;
regEle.append(comEle);
regEle.addEventListener('mousemove', (event: MouseEvent) => {
comEle.setAttribute('style', 'display: block; left: ' + event.clientX + 'px; top: ' + event.clientY + 'px');
});
regEle.addEventListener('mouseleave', (event: MouseEvent) => {
comEle.setAttribute('style', 'display: none');
});
regEle.addEventListener('click', (event: MouseEvent) => {
this.regionClicked.emit(regionIri);
});
}
}