سؤال

Ok, I've got this piece of code, trying to create a fragmented "donut" shape in canvas:

for (var i = 0; i < numberOfItems; i++) {
    var endingAngle = (startingAngle + itemLength) % (2 * Math.PI);

    menuItem[i] = new Kinetic.Shape({
        sceneFunc: function (context) {
            context.beginPath();
            context.arc(containerCenter, containerCenter, circleRadius, startingAngle, endingAngle, false);
            context.lineTo(containerCenter + smallCircleRadius * Math.cos(endingAngle), containerCenter + smallCircleRadius * Math.sin(endingAngle));
            context.arc(containerCenter, containerCenter, smallCircleRadius, endingAngle, startingAngle, true);
            context.lineTo(containerCenter + circleRadius * Math.cos(startingAngle), containerCenter + circleRadius * Math.sin(startingAngle));
            context.closePath();

            context.fillStrokeShape(this);
        },
        fill: '#00ff00',
        stroke: 'black',
        strokeWidth: 1
    });

    layer.add(menuItem[i]);
    startingAngle = endingAngle;
}

startingAngle is set from the outside of this snippet and is basically irrelevant (can have any value), numberOfItems is the number of segments, itemLength the length of each fragment as a percentage of circumference, circleRadius and smallCircleRadius the radii of the outer and inner circle of the donut shape respectively.

Now, when I try to input this as is, it won't draw anything on the canvas, just one line, which seems to be either the left-side line of the first fragment, or the right-side line of the last fragment - although that's irrelevant. If I change the code to constant values instead of the startingAngle and endingAngle, it works, and draws it correctly. What can be the issue here?

هل كانت مفيدة؟

المحلول

Your startingAngle and endingAngle variables no longer exist when the Kinetic.Shape is trying to draw itself.

Those angle variables disappear from scope when the for-loop ends.

To make the angles available in the sceneFunc you can add the angle properties to the .Shape itself:

menuItem[i].startingAngle=startingAngle;
menuItem[i].endingAngle=endingAngle;

Then you can retrieve the angles in your sceneFunc:

sceneFunc: function(ctx) {
    var startingAngle=this.startingAngle;
    var endingAngle=this.endingAngle
    ...

A Demo: http://jsfiddle.net/m1erickson/465qY/

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top