Search code examples
javascriptsvgjsxgraph

Fill the intersection area between circle and function in JSXGraph


I have a circle and simple function Math.cos(x)

I want the circle to be filled when it intersects with that function (fill only the upper side). But it's not working.

Script:

    // circle
    var point1 = app.board.create('point', [0,0], {size: 2, strokeWidth:2 })
    var point2 = app.board.create('point', [6,0], {size: 2, strokeWidth:2 })
    var circle = app.board.create('circle', [point1,point2], {strokeColor: "#f00", strokeWidth: 2 })
    
    // function
    var func = app.board.create('functiongraph',[function(x){ return Math.cos(x)}]);

    // intersection
    var curve = app.board.create('curve', [[], []], {strokeWidth: 0, fillColor: "#09f", fillOpacity: 0.8})
    curve.updateDataArray = function() {
        var a = JXG.Math.Clip.intersection(circle, func, this.board);
        this.dataX = a[0];
        this.dataY = a[1]
    };
    app.board.update()

Output

Output

Expected output (I did it on Paint)

Expected

Thank you in advance :)


Solution

  • This can easily realized with the next version of JSXGraph which will be released next week: With the inequality element the area above the cosine curve can be marked. The inequality element is a closed curve and can be intersected with a circle. In v1.2.3, the intersection does not work because of a small bug.

    For the clipping, the next version contains new elements curveintersection, curveunion, curvedifference which make it easier to use the methods of JXG.Math.Clip, but of course your approach with JXG.Math.Clip will still work.

    Here is the code:

    var f = board.create('functiongraph', ['cos(x)']);
    var ineq = board.create('inequality', [f], {
                inverse: true, fillOpacity: 0.1
            });
    var circ = board.create('circle', [[0,0], 4]);
    
    var clip = board.create('curveintersection', [ineq, circ], {
                fillColor: 'yellow', fillOpacity: 0.6
            });
    

    Intersecting inequality and circle

    Actually, the inequality element does the same as enxaneta does "by hand".