forked from rebotak/vue-winwheel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Winwheel.js
2149 lines (1810 loc) · 96.1 KB
/
Winwheel.js
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
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { TweenMax } from 'gsap'
export class Winwheel {
constructor(options, drawWheel) {
var defaultOptions = {
canvasId: 'canvas', // Id of the canvas which the wheel is to draw on to.
centerX: null, // X position of the center of the wheel. The default of these are null which means will be placed in center of the canvas.
centerY: null, // Y position of the wheel center. If left null at time of construct the center of the canvas is used.
outerRadius: null, // The radius of the outside of the wheel. If left null it will be set to the radius from the center of the canvas to its shortest side.
innerRadius: 0, // Normally 0. Allows the creation of rings / doughnuts if set to value > 0. Should not exceed outer radius.
numSegments: 1, // The number of segments. Need at least one to draw.
drawMode: 'code', // The draw mode. Possible values are 'code', 'image', 'segmentImage'. Default is code which means segments are drawn using canvas arc() function.
rotationAngle: 0, // The angle of rotation of the wheel - 0 is 12 o'clock position.
textFontFamily: 'sans-serif', // Segment text font, you should use web safe fonts.
textFontSize: 13, // Size of the segment text.
textFontWeight: 'bold', // Font weight.
textOrientation: 'horizontal', // Either horizontal, vertical, or curved.
textAlignment: 'center', // Either center, inner, or outer.
textDirection: 'normal', // Either normal or reversed. In normal mode for horizontal text in segment at 3 o'clock is correct way up, in reversed text at 9 o'clock segment is correct way up.
textMargin: null, // Margin between the inner or outer of the wheel (depends on textAlignment).
textFillStyle: 'black', // This is basically the text colour.
textStrokeStyle: null, // Basically the line colour for segment text, only looks good for large text so off by default.
textLineWidth: 1, // Width of the lines around the text. Even though this defaults to 1, a line is only drawn if textStrokeStyle specified.
fillStyle: 'silver', // The segment background colour.
strokeStyle: null, // Segment line colour. Again segment lines only drawn if this is specified.
lineWidth: 1, // Width of lines around segments.
clearTheCanvas: true, // When set to true the canvas will be cleared before the wheel is drawn.
imageOverlay: false, // If set to true in image drawing mode the outline of the segments will be displayed over the image. Does nothing in code drawMode.
drawText: true, // By default the text of the segments is rendered in code drawMode and not in image drawMode.
pointerAngle: 0, // Location of the pointer that indicates the prize when wheel has stopped. Default is 0 so the (corrected) 12 o'clock position.
wheelImage: null, // Must be set to image data in order to use image to draw the wheel - drawMode must also be 'image'.
imageDirection: 'N', // Used when drawMode is segmentImage. Default is north, can also be (E)ast, (S)outh, (W)est.
}
// -----------------------------------------
// Loop through the default options and create properties of this class set to the value for the option passed in
// or if not value for the option was passed in then to the default.
for (var key in defaultOptions) {
if (options != null && typeof options[key] !== 'undefined') {
this[key] = options[key]
} else {
this[key] = defaultOptions[key]
}
}
// Also loop though the passed in options and add anything specified not part of the class in to it as a property.
if (options != null) {
for (var key in options) {
if (typeof this[key] === 'undefined') {
this[key] = options[key]
}
}
}
// ------------------------------------------
// If the id of the canvas is set, try to get the canvas as we need it for drawing.
if (this.canvasId) {
this.canvas = document.getElementById(this.canvasId)
if (this.canvas) {
// If the centerX and centerY have not been specified in the options then default to center of the canvas
// and make the outerRadius half of the canvas width - this means the wheel will fill the canvas.
if (this.centerX == null) {
this.centerX = this.canvas.width / 2
}
if (this.centerY == null) {
this.centerY = this.canvas.height / 2
}
if (this.outerRadius == null) {
// Need to set to half the width of the shortest dimension of the canvas as the canvas may not be square.
// Minus the line segment line width otherwise the lines around the segments on the top,left,bottom,right
// side are chopped by the edge of the canvas.
if (this.canvas.width < this.canvas.height) {
this.outerRadius = this.canvas.width / 2 - this.lineWidth
} else {
this.outerRadius = this.canvas.height / 2 - this.lineWidth
}
}
// Also get a 2D context to the canvas as we need this to draw with.
this.ctx = this.canvas.getContext('2d')
} else {
this.canvas = null
this.ctx = null
}
} else {
this.cavnas = null
this.ctx = null
}
// ------------------------------------------
// Add array of segments to the wheel, then populate with segments if number of segments is specified for this object.
this.segments = new Array(null)
for (var x = 1; x <= this.numSegments; x++) {
// If options for the segments have been specified then create a segment sending these options so
// the specified values are used instead of the defaults.
if (options != null && options['segments'] && typeof options['segments'][x - 1] !== 'undefined') {
this.segments[x] = new Segment(options['segments'][x - 1])
} else {
this.segments[x] = new Segment()
}
}
// ------------------------------------------
// Call function to update the segment sizes setting the starting and ending angles.
this.updateSegmentSizes()
// If the text margin is null then set to same as font size as we want some by default.
if (this.textMargin === null) {
this.textMargin = this.textFontSize / 1.7
}
// ------------------------------------------
// If the animation options have been passed in then create animation object as a property of this class
// and pass the options to it so the animation is set. Otherwise create default animation object.
if (options != null && options['animation'] && typeof options['animation'] !== 'undefined') {
this.animation = new Animation(options['animation'])
} else {
this.animation = new Animation()
}
// ------------------------------------------
// If some pin options then create create a pin object and then pass them in.
if (options != null && options['pins'] && typeof options['pins'] !== 'undefined') {
this.pins = new Pin(options['pins'])
}
// ------------------------------------------
// On that note, if the drawMode is image change some defaults provided a value has not been specified.
if (this.drawMode == 'image' || this.drawMode == 'segmentImage') {
// Remove grey fillStyle.
if (typeof options['fillStyle'] === 'undefined') {
this.fillStyle = null
}
// Set strokeStyle to red.
if (typeof options['strokeStyle'] === 'undefined') {
this.strokeStyle = 'red'
}
// Set drawText to false as we will assume any text is part of the image.
if (typeof options['drawText'] === 'undefined') {
this.drawText = false
}
// Also set the lineWidth to 1 so that segment overlay will look correct.
if (typeof options['lineWidth'] === 'undefined') {
this.lineWidth = 1
}
// Set drawWheel to false as normally the image needs to be loaded first.
if (typeof drawWheel === 'undefined') {
drawWheel = false
}
} else {
// When in code drawMode the default is the wheel will draw.
if (typeof drawWheel === 'undefined') {
drawWheel = true
}
}
// Create pointer guide.
if (options != null && options['pointerGuide'] && typeof options['pointerGuide'] !== 'undefined') {
this.pointerGuide = new PointerGuide(options['pointerGuide'])
} else {
this.pointerGuide = new PointerGuide()
}
// Finally if drawWheel is true then call function to render the wheel, segment text, overlay etc.
if (drawWheel == true) {
this.draw(this.clearTheCanvas)
} else if (this.drawMode == 'segmentImage') {
// If segment image then loop though all the segments and load the images for them setting a callback
// which will call the draw function of the wheel once all the images have been loaded.
winwheelToDrawDuringAnimation = this
winhweelAlreadyDrawn = false
for (var y = 1; y <= this.numSegments; y++) {
if (this.segments[y].image !== null) {
this.segments[y].imgData = new Image()
this.segments[y].imgData.onload = winwheelLoadedImage
this.segments[y].imgData.src = this.segments[y].image
}
}
}
}
// ====================================================================================================================
// This function sorts out the segment sizes. Some segments may have set sizes, for the others what is left out of
// 360 degrees is shared evenly. What this function actually does is set the start and end angle of the arcs.
// ====================================================================================================================
updateSegmentSizes() {
// If this object actually contains some segments
if (this.segments) {
// First add up the arc used for the segments where the size has been set.
var arcUsed = 0
var numSet = 0
// Remember, to make it easy to access segments, the position of the segments in the array starts from 1 (not 0).
for (var x = 1; x <= this.numSegments; x++) {
if (this.segments[x].size !== null) {
arcUsed += this.segments[x].size
numSet++
}
}
var arcLeft = 360 - arcUsed
// Create variable to hold how much each segment with non-set size will get in terms of degrees.
var degreesEach = 0
if (arcLeft > 0) {
degreesEach = arcLeft / (this.numSegments - numSet)
}
// ------------------------------------------
// Now loop though and set the start and end angle of each segment.
var currentDegree = 0
for (var x = 1; x <= this.numSegments; x++) {
// Set start angle.
this.segments[x].startAngle = currentDegree
// If the size is set then add this to the current degree to get the end, else add the degreesEach to it.
if (this.segments[x].size) {
currentDegree += this.segments[x].size
} else {
currentDegree += degreesEach
}
// Set end angle.
this.segments[x].endAngle = currentDegree
}
}
}
// ====================================================================================================================
// This function clears the canvas. Will wipe anything else which happens to be drawn on it.
// ====================================================================================================================
clearCanvas() {
if (this.ctx) {
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height)
}
}
// ====================================================================================================================
// This function draws / re-draws the wheel on the canvas therefore rendering any changes.
// ====================================================================================================================
draw(clearTheCanvas) {
// If have the canvas context.
if (this.ctx) {
// Clear the canvas, unless told not to.
if (typeof clearTheCanvas !== 'undefined') {
if (clearTheCanvas == true) {
this.clearCanvas()
}
} else {
this.clearCanvas()
}
// Call functions to draw the segments and then segment text.
if (this.drawMode == 'image') {
// Draw the wheel by loading and drawing an image such as a png on the canvas.
this.drawWheelImage()
// If we are to draw the text, do so before the overlay is drawn
// as this allows the overlay to be used to create some interesting effects.
if (this.drawText == true) {
this.drawSegmentText()
}
// If image overlay is true then call function to draw the segments over the top of the image.
// This is useful during development to check alignment between where the code thinks the segments are and where they appear on the image.
if (this.imageOverlay == true) {
this.drawSegments()
}
} else if (this.drawMode == 'segmentImage') {
// Draw the wheel by rendering the image for each segment.
this.drawSegmentImages()
// If we are to draw the text, do so before the overlay is drawn
// as this allows the overlay to be used to create some interesting effects.
if (this.drawText == true) {
this.drawSegmentText()
}
// If image overlay is true then call function to draw the segments over the top of the image.
// This is useful during development to check alignment between where the code thinks the segments are and where they appear on the image.
if (this.imageOverlay == true) {
this.drawSegments()
}
} else {
// The default operation is to draw the segments using code via the canvas arc() method.
this.drawSegments()
// The text is drawn on top.
if (this.drawText == true) {
this.drawSegmentText()
}
}
// If this class has pins.
if (typeof this.pins !== 'undefined') {
// If they are to be visible then draw them.
if (this.pins.visible == true) this.drawPins()
}
// If pointer guide is display property is set to true then call function to draw the pointer guide.
if (this.pointerGuide.display == true) {
this.drawPointerGuide()
}
}
}
// ====================================================================================================================
// Draws the pins around the outside of the wheel.
// ====================================================================================================================
drawPins() {
if (this.pins && this.pins.number) {
// Work out the angle to draw each pin a which is simply 360 / the number of pins as they space evenly around.
//++ There is a slight oddity with the pins in that there is a pin at 0 and also one at 360 and these will be drawn
//++ directly over the top of each other. Also pins are 0 indexed which could possibly cause some confusion
//++ with the getCurrentPin function - for now this is just used for audio so probably not a problem.
var pinSpacing = 360 / this.pins.number
for (var i = 1; i <= this.pins.number; i++) {
this.ctx.save()
// Set the stroke style and line width.
this.ctx.strokeStyle = this.pins.strokeStyle
this.ctx.lineWidth = this.pins.lineWidth
this.ctx.fillStyle = this.pins.fillStyle
// Move to the center.
this.ctx.translate(this.centerX, this.centerY)
// Rotate to to the pin location which is i * the pinSpacing.
this.ctx.rotate(this.degToRad(i * pinSpacing + this.rotationAngle))
// Move back out.
this.ctx.translate(-this.centerX, -this.centerY)
// Create a path for the pin circle.
this.ctx.beginPath()
// x, y, radius, startAngle, endAngle.
this.ctx.arc(
this.centerX,
this.centerY - this.outerRadius + this.pins.outerRadius + this.pins.margin,
this.pins.outerRadius,
0,
2 * Math.PI
)
if (this.pins.fillStyle) this.ctx.fill()
if (this.pins.strokeStyle) this.ctx.stroke()
this.ctx.restore()
}
}
}
// ====================================================================================================================
// Draws a line from the center of the wheel to the outside at the angle where the code thinks the pointer is.
// ====================================================================================================================
drawPointerGuide() {
// If have canvas context.
if (this.ctx) {
this.ctx.save()
// Rotate the canvas to the line goes towards the location of the pointer.
this.ctx.translate(this.centerX, this.centerY)
this.ctx.rotate(this.degToRad(this.pointerAngle))
this.ctx.translate(-this.centerX, -this.centerY)
// Set line colour and width.
this.ctx.strokeStyle = this.pointerGuide.strokeStyle
this.ctx.lineWidth = this.pointerGuide.lineWidth
// Draw from the center of the wheel outwards past the wheel outer radius.
this.ctx.beginPath()
this.ctx.moveTo(this.centerX, this.centerY)
this.ctx.lineTo(this.centerX, -(this.outerRadius / 4))
this.ctx.stroke()
this.ctx.restore()
}
}
// ====================================================================================================================
// This function takes an image such as PNG and draws it on the canvas making its center at the centerX and center for the wheel.
// ====================================================================================================================
drawWheelImage() {
// Double check the wheelImage property of this class is not null. This does not actually detect that an image
// source was set and actually loaded so might get error if this is not the case. This is why the initial call
// to draw() should be done from a wheelImage.onload callback as detailed in example documentation.
if (this.wheelImage != null) {
// Work out the correct X and Y to draw the image at. We need to get the center point of the image
// aligned over the center point of the wheel, we can't just place it at 0, 0.
var imageLeft = this.centerX - this.wheelImage.height / 2
var imageTop = this.centerY - this.wheelImage.width / 2
// Rotate and then draw the wheel.
// We must rotate by the rotationAngle before drawing to ensure that image wheels will spin.
this.ctx.save()
this.ctx.translate(this.centerX, this.centerY)
this.ctx.rotate(this.degToRad(this.rotationAngle))
this.ctx.translate(-this.centerX, -this.centerY)
this.ctx.drawImage(this.wheelImage, imageLeft, imageTop)
this.ctx.restore()
}
}
// ====================================================================================================================
// This function draws the wheel on the canvas by rendering the image for each segment.
// ====================================================================================================================
drawSegmentImages() {
// Again check have context in case this function was called directly and not via draw function.
if (this.ctx) {
// Draw the segments if there is at least one in the segments array.
if (this.segments) {
// Loop though and output all segments - position 0 of the array is not used, so start loop from index 1
// this is to avoid confusion when talking about the first segment.
for (var x = 1; x <= this.numSegments; x++) {
// Get the segment object as we need it to read options from.
var seg = this.segments[x]
// Check image has loaded so a property such as height has a value.
if (seg.imgData.height) {
// Work out the correct X and Y to draw the image at which depends on the direction of the image.
// Images can be created in 4 directions. North, South, East, West.
// North: Outside at top, inside at bottom. Sits evenly over the 0 degrees angle.
// South: Outside at bottom, inside at top. Sits evenly over the 180 degrees angle.
// East: Outside at right, inside at left. Sits evenly over the 90 degrees angle.
// West: Outside at left, inside at right. Sits evenly over the 270 degrees angle.
var imageLeft = 0
var imageTop = 0
var imageAngle = 0
var imageDirection = ''
if (seg.imageDirection !== null) imageDirection = seg.imageDirection
else imageDirection = this.imageDirection
if (imageDirection == 'S') {
// Left set so image sits half/half over the 180 degrees point.
imageLeft = this.centerX - seg.imgData.width / 2
// Top so image starts at the centerY.
imageTop = this.centerY
// Angle to draw the image is its starting angle + half its size.
// Here we add 180 to the angle to the segment is poistioned correctly.
imageAngle = seg.startAngle + 180 + (seg.endAngle - seg.startAngle) / 2
} else if (imageDirection == 'E') {
// Left set so image starts and the center point.
imageLeft = this.centerX
// Top is so that it sits half/half over the 90 degree point.
imageTop = this.centerY - seg.imgData.height / 2
// Again get the angle in the center of the segment and add it to the rotation angle.
// this time we need to add 270 to that to the segment is rendered the correct place.
imageAngle = seg.startAngle + 270 + (seg.endAngle - seg.startAngle) / 2
} else if (imageDirection == 'W') {
// Left is the centerX minus the width of the image.
imageLeft = this.centerX - seg.imgData.width
// Top is so that it sits half/half over the 270 degree point.
imageTop = this.centerY - seg.imgData.height / 2
// Again get the angle in the center of the segment and add it to the rotation angle.
// this time we need to add 90 to that to the segment is rendered the correct place.
imageAngle = seg.startAngle + 90 + (seg.endAngle - seg.startAngle) / 2
} // North is the default.
else {
// Left set so image sits half/half over the 0 degrees point.
imageLeft = this.centerX - seg.imgData.width / 2
// Top so image is its height out (above) the center point.
imageTop = this.centerY - seg.imgData.height
// Angle to draw the image is its starting angle + half its size.
// this sits it half/half over the center angle of the segment.
imageAngle = seg.startAngle + (seg.endAngle - seg.startAngle) / 2
}
// --------------------------------------------------
// Rotate to the position of the segment and then draw the image.
this.ctx.save()
this.ctx.translate(this.centerX, this.centerY)
// So math here is the rotation angle of the wheel plus half way between the start and end angle of the segment.
this.ctx.rotate(this.degToRad(this.rotationAngle + imageAngle))
this.ctx.translate(-this.centerX, -this.centerY)
// Draw the image.
this.ctx.drawImage(seg.imgData, imageLeft, imageTop)
this.ctx.restore()
} else {
console.log('Segment ' + x + ' imgData is not loaded')
}
}
}
}
}
// ====================================================================================================================
// This function draws the wheel on the page by rendering the segments on the canvas.
// ====================================================================================================================
drawSegments() {
// Again check have context in case this function was called directly and not via draw function.
if (this.ctx) {
// Draw the segments if there is at least one in the segments array.
if (this.segments) {
// Loop though and output all segments - position 0 of the array is not used, so start loop from index 1
// this is to avoid confusion when talking about the first segment.
for (var x = 1; x <= this.numSegments; x++) {
// Get the segment object as we need it to read options from.
var seg = this.segments[x]
var fillStyle
var lineWidth
var strokeStyle
// Set the variables that defined in the segment, or use the default options.
if (seg.fillStyle !== null) fillStyle = seg.fillStyle
else fillStyle = this.fillStyle
this.ctx.fillStyle = fillStyle
if (seg.lineWidth !== null) lineWidth = seg.lineWidth
else lineWidth = this.lineWidth
this.ctx.lineWidth = lineWidth
if (seg.strokeStyle !== null) strokeStyle = seg.strokeStyle
else strokeStyle = this.strokeStyle
this.ctx.strokeStyle = strokeStyle
// Check there is a strokeStyle or fillStyle, if either the the segment is invisible so should not
// try to draw it otherwise a path is began but not ended.
if (strokeStyle || fillStyle) {
// ----------------------------------
// Begin a path as the segment consists of an arc and 2 lines.
this.ctx.beginPath()
// If don't have an inner radius then move to the center of the wheel as we want a line out from the center
// to the start of the arc for the outside of the wheel when we arc. Canvas will draw the connecting line for us.
if (!this.innerRadius) {
this.ctx.moveTo(this.centerX, this.centerY)
} else {
//++ do need to draw the starting line in the correct x + y based on the start angle
//++ otherwise as seen when the wheel does not use up 360 the starting segment is missing the stroked side,
}
// Draw the outer arc of the segment clockwise in direction -->
this.ctx.arc(
this.centerX,
this.centerY,
this.outerRadius,
this.degToRad(seg.startAngle + this.rotationAngle - 90),
this.degToRad(seg.endAngle + this.rotationAngle - 90),
false
)
if (this.innerRadius) {
// Draw another arc, this time anticlockwise <-- at the innerRadius between the end angle and the start angle.
// Canvas will draw a connecting line from the end of the outer arc to the beginning of the inner arc completing the shape.
//++ Think the reason the lines are thinner for 2 of the segments is because the thing auto chops part of it
//++ when doing the next one. Again think that actually drawing the lines will help.
this.ctx.arc(
this.centerX,
this.centerY,
this.innerRadius,
this.degToRad(seg.endAngle + this.rotationAngle - 90),
this.degToRad(seg.startAngle + this.rotationAngle - 90),
true
)
} else {
// If no inner radius then we draw a line back to the center of the wheel.
this.ctx.lineTo(this.centerX, this.centerY)
}
// Fill and stroke the segment. Only do either if a style was specified, if the style is null then
// we assume the developer did not want that particular thing.
// For example no stroke style so no lines to be drawn.
if (fillStyle) this.ctx.fill()
if (strokeStyle) this.ctx.stroke()
}
}
}
}
}
// ====================================================================================================================
// This draws the text on the segments using the specified text options.
// ====================================================================================================================
drawSegmentText() {
// Again only draw the text if have a canvas context.
if (this.ctx) {
// Declare variables to hold the values. These are populated either with the value for the specific segment,
// or if not specified then the global default value.
var fontFamily
var fontSize
var fontWeight
var orientation
var alignment
var direction
var margin
var fillStyle
var strokeStyle
var lineWidth
var fontSetting
// Loop though all the segments.
for (var x = 1; x <= this.numSegments; x++) {
// Save the context so it is certain that each segment text option will not affect the other.
this.ctx.save()
// Get the segment object as we need it to read options from.
var seg = this.segments[x]
// Check is text as no point trying to draw if there is no text to render.
if (seg.text) {
// Set values to those for the specific segment or use global default if null.
if (seg.textFontFamily !== null) fontFamily = seg.textFontFamily
else fontFamily = this.textFontFamily
if (seg.textFontSize !== null) fontSize = seg.textFontSize
else fontSize = this.textFontSize
if (seg.textFontWeight !== null) fontWeight = seg.textFontWeight
else fontWeight = this.textFontWeight
if (seg.textOrientation !== null) orientation = seg.textOrientation
else orientation = this.textOrientation
if (seg.textAlignment !== null) alignment = seg.textAlignment
else alignment = this.textAlignment
if (seg.textDirection !== null) direction = seg.textDirection
else direction = this.textDirection
if (seg.textMargin !== null) margin = seg.textMargin
else margin = this.textMargin
if (seg.textFillStyle !== null) fillStyle = seg.textFillStyle
else fillStyle = this.textFillStyle
if (seg.textStrokeStyle !== null) strokeStyle = seg.textStrokeStyle
else strokeStyle = this.textStrokeStyle
if (seg.textLineWidth !== null) lineWidth = seg.textLineWidth
else lineWidth = this.textLineWidth
// ------------------------------
// We need to put the font bits together in to one string.
fontSetting = ''
if (fontWeight != null) fontSetting += fontWeight + ' '
if (fontSize != null) fontSetting += fontSize + 'px ' // Fonts on canvas are always a px value.
if (fontFamily != null) fontSetting += fontFamily
// Now set the canvas context to the decided values.
this.ctx.font = fontSetting
this.ctx.fillStyle = fillStyle
this.ctx.strokeStyle = strokeStyle
this.ctx.lineWidth = lineWidth
// Split the text in to multiple lines on the \n character.
var lines = seg.text.split('\n')
// Figure out the starting offset for the lines as when there are multiple lines need to center the text
// vertically in the segment (when thinking of normal horozontal text).
var lineOffset = 0 - fontSize * (lines.length / 2) + fontSize / 2
// The offset works great for horozontal and vertial text, also centered curved. But when the text is curved
// and the alignment is outer then the multiline text should not have some text outside the wheel. Same if inner curved.
if (orientation == 'curved' && (alignment == 'inner' || alignment == 'outer')) {
lineOffset = 0
}
for (var i = 0; i < lines.length; i++) {
// ---------------------------------
// If direction is reversed then do things differently than if normal (which is the default - see further down)
if (direction == 'reversed') {
// When drawing reversed or 'upside down' we need to do some trickery on our part.
// The canvas text rendering function still draws the text left to right and the correct way up,
// so we need to overcome this with rotating the opposite side of the wheel the correct way up then pulling the text
// through the center point to the correct segment it is supposed to be on.
if (orientation == 'horizontal') {
if (alignment == 'inner') this.ctx.textAlign = 'right'
else if (alignment == 'outer') this.ctx.textAlign = 'left'
else this.ctx.textAlign = 'center'
this.ctx.textBaseline = 'middle'
// Work out the angle to rotate the wheel, this is in the center of the segment but on the opposite side of the wheel which is why do -180.
var textAngle = this.degToRad(
seg.endAngle - (seg.endAngle - seg.startAngle) / 2 + this.rotationAngle - 90 - 180
)
this.ctx.save()
this.ctx.translate(this.centerX, this.centerY)
this.ctx.rotate(textAngle)
this.ctx.translate(-this.centerX, -this.centerY)
if (alignment == 'inner') {
// In reversed state the margin is subtracted from the innerX.
// When inner the inner radius also comes in to play.
if (fillStyle)
this.ctx.fillText(
lines[i],
this.centerX - this.innerRadius - margin,
this.centerY + lineOffset
)
if (strokeStyle)
this.ctx.strokeText(
lines[i],
this.centerX - this.innerRadius - margin,
this.centerY + lineOffset
)
} else if (alignment == 'outer') {
// In reversed state the position is the center minus the radius + the margin for outer aligned text.
if (fillStyle)
this.ctx.fillText(
lines[i],
this.centerX - this.outerRadius + margin,
this.centerY + lineOffset
)
if (strokeStyle)
this.ctx.strokeText(
lines[i],
this.centerX - this.outerRadius + margin,
this.centerY + lineOffset
)
} else {
// In reversed state the everything in minused.
if (fillStyle)
this.ctx.fillText(
lines[i],
this.centerX -
this.innerRadius -
(this.outerRadius - this.innerRadius) / 2 -
margin,
this.centerY + lineOffset
)
if (strokeStyle)
this.ctx.strokeText(
lines[i],
this.centerX -
this.innerRadius -
(this.outerRadius - this.innerRadius) / 2 -
margin,
this.centerY + lineOffset
)
}
this.ctx.restore()
} else if (orientation == 'vertical') {
// See normal code further down for comments on how it works, this is similar by plus/minus is reversed.
this.ctx.textAlign = 'center'
// In reversed mode this are reversed.
if (alignment == 'inner') this.ctx.textBaseline = 'top'
else if (alignment == 'outer') this.ctx.textBaseline = 'bottom'
else this.ctx.textBaseline = 'middle'
var textAngle = seg.endAngle - (seg.endAngle - seg.startAngle) / 2 - 180
textAngle += this.rotationAngle
this.ctx.save()
this.ctx.translate(this.centerX, this.centerY)
this.ctx.rotate(this.degToRad(textAngle))
this.ctx.translate(-this.centerX, -this.centerY)
if (alignment == 'outer') var yPos = this.centerY + this.outerRadius - margin
else if (alignment == 'inner') var yPos = this.centerY + this.innerRadius + margin
// I have found that the text looks best when a fraction of the font size is shaved off.
var yInc = fontSize - fontSize / 9
// Loop though and output the characters.
if (alignment == 'outer') {
// In reversed mode outer means text in 6 o'clock segment sits at bottom of the wheel and we draw up.
for (var c = lines[i].length - 1; c >= 0; c--) {
character = lines[i].charAt(c)
if (fillStyle) this.ctx.fillText(character, this.centerX + lineOffset, yPos)
if (strokeStyle) this.ctx.strokeText(character, this.centerX + lineOffset, yPos)
yPos -= yInc
}
} else if (alignment == 'inner') {
// In reversed mode inner text is drawn from top of segment at 6 o'clock position to bottom of the wheel.
for (var c = 0; c < lines[i].length; c++) {
character = lines[i].charAt(c)
if (fillStyle) this.ctx.fillText(character, this.centerX + lineOffset, yPos)
if (strokeStyle) this.ctx.strokeText(character, this.centerX + lineOffset, yPos)
yPos += yInc
}
} else if (alignment == 'center') {
// Again for reversed this is the opposite of before.
// If there is more than one character in the text then an adjustment to the position needs to be done.
// What we are aiming for is to position the center of the text at the center point between the inner and outer radius.
var centerAdjustment = 0
if (lines[i].length > 1) {
centerAdjustment = (yInc * (lines[i].length - 1)) / 2
}
var yPos =
this.centerY +
this.innerRadius +
(this.outerRadius - this.innerRadius) / 2 +
centerAdjustment +
margin
for (var c = lines[i].length - 1; c >= 0; c--) {
character = lines[i].charAt(c)
if (fillStyle) this.ctx.fillText(character, this.centerX + lineOffset, yPos)
if (strokeStyle) this.ctx.strokeText(character, this.centerX + lineOffset, yPos)
yPos -= yInc
}
}
this.ctx.restore()
} else if (orientation == 'curved') {
// There is no built in canvas function to draw text around an arc,
// so we need to do this ourselves.
var radius = 0
// Set the alignment of the text - inner, outer, or center by calculating
// how far out from the center point of the wheel the text is drawn.
if (alignment == 'inner') {
// When alignment is inner the radius is the innerRadius plus any margin.
radius = this.innerRadius + margin
this.ctx.textBaseline = 'top'
} else if (alignment == 'outer') {
// Outer it is the outerRadius minus any margin.
radius = this.outerRadius - margin
this.ctx.textBaseline = 'bottom'
// We need to adjust the radius in this case to take in to multiline text.
// In this case the radius needs to be further out, not at the inner radius.
radius -= fontSize * (lines.length - 1)
} else if (alignment == 'center') {
// When center we want the text halfway between the inner and outer radius.
radius = this.innerRadius + margin + (this.outerRadius - this.innerRadius) / 2
this.ctx.textBaseline = 'middle'
}
// Set the angle to increment by when looping though and outputting the characters in the text
// as we do this by rotating the wheel small amounts adding each character.
var anglePerChar = 0
var drawAngle = 0
// If more than one character in the text then...
if (lines[i].length > 1) {
// Text is drawn from the left.
this.ctx.textAlign = 'left'
// Work out how much angle the text rendering loop below needs to rotate by for each character to render them next to each other.
// I have discovered that 4 * the font size / 10 at 100px radius is the correct spacing for between the characters
// using a monospace font, non monospace may look a little odd as in there will appear to be extra spaces between chars.
anglePerChar = 4 * (fontSize / 10)
// Work out what percentage the radius the text will be drawn at is of 100px.
radiusPercent = 100 / radius
// Then use this to scale up or down the anglePerChar value.
// When the radius is less than 100px we need more angle between the letters, when radius is greater (so the text is further
// away from the center of the wheel) the angle needs to be less otherwise the characters will appear further apart.
anglePerChar = anglePerChar * radiusPercent
// Next we want the text to be drawn in the middle of the segment, without this it would start at the beginning of the segment.
// To do this we need to work out how much arc the text will take up in total then subtract half of this from the center
// of the segment so that it sits centred.
totalArc = anglePerChar * lines[i].length
// Now set initial draw angle to half way between the start and end of the segment.
drawAngle = seg.startAngle + ((seg.endAngle - seg.startAngle) / 2 - totalArc / 2)
} else {
// The initial draw angle is the center of the segment when only one character.
drawAngle = seg.startAngle + (seg.endAngle - seg.startAngle) / 2
// To ensure is dead-center the text alignment also needs to be centered.
this.ctx.textAlign = 'center'
}
// ----------------------
// Adjust the initial draw angle as needed to take in to account the rotationAngle of the wheel.
drawAngle += this.rotationAngle
// And as with other 'reverse' text direction functions we need to subtract 180 degrees from the angle
// because when it comes to draw the characters in the loop below we add the radius instead of subtract it.
drawAngle -= 180
// ----------------------
// Now the drawing itself.
// In reversed direction mode we loop through the characters in the text backwards in order for them to appear on screen correctly
for (c = lines[i].length; c >= 0; c--) {
this.ctx.save()
character = lines[i].charAt(c)
// Rotate the wheel to the draw angle as we need to add the character at this location.
this.ctx.translate(this.centerX, this.centerY)
this.ctx.rotate(this.degToRad(drawAngle))
this.ctx.translate(-this.centerX, -this.centerY)
// Now draw the character directly below the center point of the wheel at the appropriate radius.
// Note in the reversed mode we add the radius to the this.centerY instead of subtract.
if (strokeStyle)
this.ctx.strokeText(character, this.centerX, this.centerY + radius + lineOffset)
if (fillStyle)
this.ctx.fillText(character, this.centerX, this.centerY + radius + lineOffset)
// Increment the drawAngle by the angle per character so next loop we rotate
// to the next angle required to draw the character at.
drawAngle += anglePerChar
this.ctx.restore()
}
}
} else {
// Normal direction so do things normally.
// Check text orientation, of horizontal then reasonably straight forward, if vertical then a bit more work to do.
if (orientation == 'horizontal') {
// Based on the text alignment, set the correct value in the context.
if (alignment == 'inner') this.ctx.textAlign = 'left'
else if (alignment == 'outer') this.ctx.textAlign = 'right'
else this.ctx.textAlign = 'center'
// Set this too.
this.ctx.textBaseline = 'middle'
// Work out the angle around the wheel to draw the text at, which is simply in the middle of the segment the text is for.
// The rotation angle is added in to correct the annoyance with the canvas arc drawing functions which put the 0 degrees at the 3 oclock
var textAngle = this.degToRad(
seg.endAngle - (seg.endAngle - seg.startAngle) / 2 + this.rotationAngle - 90
)
// We need to rotate in order to draw the text because it is output horizontally, so to
// place correctly around the wheel for all but a segment at 3 o'clock we need to rotate.
this.ctx.save()
this.ctx.translate(this.centerX, this.centerY)
this.ctx.rotate(textAngle)
this.ctx.translate(-this.centerX, -this.centerY)
// --------------------------
// Draw the text based on its alignment adding margin if inner or outer.
if (alignment == 'inner') {
// Inner means that the text is aligned with the inner of the wheel. If looking at a segment in in the 3 o'clock position
// it would look like the text is left aligned within the segment.
// Because the segments are smaller towards the inner of the wheel, in order for the text to fit is is a good idea that
// a margin is added which pushes the text towards the outer a bit.
// The inner radius also needs to be taken in to account as when inner aligned.
// If fillstyle is set the draw the text filled in.
if (fillStyle)
this.ctx.fillText(
lines[i],
this.centerX + this.innerRadius + margin,
this.centerY + lineOffset
)
// If stroke style is set draw the text outline.
if (strokeStyle)
this.ctx.strokeText(
lines[i],
this.centerX + this.innerRadius + margin,
this.centerY + lineOffset
)
} else if (alignment == 'outer') {
// Outer means the text is aligned with the outside of the wheel, so if looking at a segment in the 3 o'clock position
// it would appear the text is right aligned. To position we add the radius of the wheel in to the equation
// and subtract the margin this time, rather than add it.
// I don't understand why, but in order of the text to render correctly with stroke and fill, the stroke needs to
// come first when drawing outer, rather than second when doing inner.
if (fillStyle)
this.ctx.fillText(
lines[i],