Winwheel.js tutorial: #4 Altering Segment Properties


This tutorial demonstrates altering segment properties after the wheel has been created.


To do this you simply access the desired segment using the segments property of the wheel class, then use the dot operator (period) to access the property you want to get or set. The segments property is an array of the segment objects which make up the wheel.


After altering the properties you need to call the draw() method in order for the changes to the wheel to be rendered. If the changes you made are not appearing double-check that you are doing this!


Here I change the fillStyle of the segments when the "Change Colours" button is pressed.



ExampleCode

<script>
    let theWheel = new Winwheel({
        'numSegments' : 4,
        'segments'    :
        [
            {'fillStyle' : '#eae56f', 'text' : 'Segment 1'},
            {'fillStyle' : '#89f26e', 'text' : 'Segment 2'},
            {'fillStyle' : '#7de6ef', 'text' : 'Segment 3'},
            {'fillStyle' : '#e7706f', 'text' : 'Segment 4'}
        ]
    });

    function changeColours()
    {
        // Change colours as desired by accessing the segment via the segments array
        // of the wheel object (note first array position is 1 not 0).
        let temp = theWheel.segments[1].fillStyle;
        theWheel.segments[1].fillStyle = theWheel.segments[2].fillStyle;
        theWheel.segments[2].fillStyle = theWheel.segments[3].fillStyle;
        theWheel.segments[3].fillStyle = theWheel.segments[4].fillStyle;
        theWheel.segments[4].fillStyle = temp;

        // The draw method of the wheel object must be called
        // in order for the changes to be rendered.
        theWheel.draw();
    }
</script>

<button onClick="changeColours();">Change Colours</button>


Output on the Canvas

Canvas not supported, use another browser. Click this -> <- Click this


Additional Notes

Note that the segments array starts from 1 not 0. I deliberately did this to avoid any confusion when talking about the first segment, second segment etc. By starting at 1 the array index matches the segment number (One=1, Two=2, and so on).


Remember to call the draw() function after making any changes to wheel in order for these changes to be rendered.


You also alter the global wheel properties by using the dot operator, i.e. theWheel.fillStyle = '#DB0058'; at any time after the wheel object has been created.



Previous:
< #3 Segment Colour and Text
Next:
#5: Adding and Removing Segments >