Search code examples
jsxgraph

how to scale line width depending on screen size in JSXGraph


Probably this has been asked and answered before, but I could not find the answer either here or in the JSXgraph reference.

Is there a way to dynamically change the stroke width of a line when the size of the board (on the screen) is changing? Ideally I would like to set a percentage value, but I am not sure if this is possible, since (as far as I understand) the values for possible stroke widths are integers.

What I am looking for is a solution that sets different stroke width values when the screen size on the viewing device is changing. Any help would be appreciated.


Solution

  • Here is a minimal way to make the scale width dependent on the width of the JSXGraph board:

    const board = JXG.JSXGraph.initBoard('jxgbox', { 
        boundingbox: [-5, 5, 5, -5], axis:true
    });
    
    var sizeFunc = () => board.canvasWidth / 200;
    var line = board.create('line', [[-3,-1], [2, 3]], {strokeWidth: sizeFunc});
    

    See it live at https://jsfiddle.net/art5g2u7/. Since some years, stroke widths can be given as arbitrary floating point numbers. Only early IE versions needed integer numbers (as far as I remember).

    Update, addressing the follow-up questions by Ferenc Beleznay:

    If different scale factors for different elements are needed, be aware that the JSXGraph attribute's value still has to be a function. In the jsfiddle in the comment the code looks like this:

    var sizeFunc = (scale) => board.canvasWidth / scale;    
    var resetLogo1a = board.create('arc', 
           [[3,-6], [3,-5.5], [3.5,-6]],
           {highlight: false, ...,
            center:{visible:false}, 
            strokeWidth: sizeFunc(100)
           });
    

    That is, the function sizeFunc is evaluated once when the arc element is created and returns a number. This number will then become the (fixed) stroke width of that element. However, what is needed in this situation is a function, i.e. sizeFunc has to return a function, like this:

    var sizeFunc = function(scale) { return () => board.canvasWidth / scale; };    
    var resetLogo1a = board.create('arc', 
           [[3,-6], [3,-5.5], [3.5,-6]],
           {highlight: false, ...,
            center:{visible:false}, 
            strokeWidth: sizeFunc(100)
           });
    

    Now, the value of the attribute strokeWidth is a function. See it live at https://jsfiddle.net/qyh1oz3m/.