Search code examples
html5-canvascytoscape.jscytoscape

How do I get a reference to Cytoscape Canvas Context?


I need a reference to Cytoscape Canvas Object and it's 2D context. How can I do this? I don't see any "id" attribute on the canvas.

Thanks


Solution

  • You could acquire Cytoscape­'s canvas element and its context in the following way ...

    var canvas = document.querySelector('canvas[data-id="layer2-node"]');
    var context = canvas.getContext('2d');
    

    Here's an example, showing how you could use the context to draw something on the canvas ...

    var cy = cytoscape({
        container: document.getElementById('cy'),
        elements: [
            { data: { id: 'a' } },
            { data: { id: 'b' } },
            {
                data: {
                    id: 'ab',
                    source: 'a',
                    target: 'b'
                }
            }
        ]
    });
    
    var canvas = document.querySelector('canvas[data-id="layer2-node"]');
    var context = canvas.getContext('2d');
    
    // draw rectangle using general canvas method
    function draw() {
        context.fillRect(canvas.width / 2.1, 60, 30, 30);
        requestAnimationFrame(draw);
    }
    draw();
    <script src="https://cdnjs.cloudflare.com/ajax/libs/cytoscape/3.1.0/cytoscape.min.js"></script>
    <div id="cy" style="width: 100%; height: 100%; position: absolute; top: 0px; left: 0px;"></div>