Aravind
Aravind

Reputation: 590

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

Upvotes: 2

Views: 1590

Answers (3)

Alex Nault
Alex Nault

Reputation: 700

Following @maxkfranz's (Cytoscape dev) recommendations, I develop a lightweight Cytoscape.js extension called cytoscape-canvas that creates a canvas over and/or under a graph. It enables that full flexibility you're looking for.

Preview

If you're interested, check out the readme!

Upvotes: 2

maxkfranz
maxkfranz

Reputation: 12250

You shouldn't try to grab Cytoscape's canvas. Cytoscape uses several canvases for performance reasons, and you can't guarantee which type of context is valid. It may use context2d or it may use webgl for performance. Even if a context2d is uses, you can't keep track of when or what state changes (e.g. transforms) have happened on the canvas. And by making your own changes, you may break assumptions Cytoscape has made.

If you want overlay content, you should make your own overlay canvas. You generally shouldn't modify dom elements or js objects that belong to a lib outside of public/documented API.

Upvotes: 1

ɢʀᴜɴᴛ
ɢʀᴜɴᴛ

Reputation: 32889

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>

Upvotes: 2

Related Questions