我如何获得对 Cytoscape Canvas 上下文的引用?

How do I get a reference to Cytoscape Canvas Context?

我需要引用 Cytoscape Canvas 对象及其二维上下文。我怎样才能做到这一点?我在 canvas.

上没有看到任何 "id" 属性

谢谢

您可以通过以下方式获取 Cytoscape canvas 元素及其上下文 ...

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

这是一个示例,展示了如何使用上下文在 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>

你不应该试图抓住 Cytoscape 的 canvas。出于性能原因,Cytoscape 使用多个 canvases,并且您无法保证哪种类型的上下文有效。它可以使用 context2d 或者它可以使用 webgl 来提高性能。即使使用了 context2d,您也无法跟踪 canvas 上发生的状态更改(例如转换)的时间或内容。通过进行您自己的更改,您可能会打破 Cytoscape 所做的假设。

如果你想要覆盖内容,你应该制作自己的覆盖canvas。您通常不应修改属于 public/documented API.

之外的库的 dom 元素或 js 对象

按照@maxkfranz (Cytoscape dev) 的建议,我开发了一个名为 cytoscape-canvas 的轻量级 Cytoscape.js 扩展,它在图表下的 and/or 上创建了 canvas。它可以实现您正在寻找的完全灵活性。

如果您有兴趣,请查看 readme