根据建议here,我应该使用 画布渲染器 ,以便可以在节点中显示图像。首先,我创建了一个 graphClass :
expr
然后,我创建每个节点:
graphClass.g = {
nodes: [],
edges: []
}
其中graphClass.g.nodes.push({
id: 'n' + data.id,
label: data.username,
x: Math.random(),
y: Math.random(),
size: 20,
type: 'image',
url: data.picture
});
是图片网址。
(边缘与此无关)
最后,我实例化Sigma:
data.picture
除了图像之外,这可以按预期工作。我无法看到它们,而是显示黑色节点。我知道我做错了什么?
答案 0 :(得分:0)
我知道了。我必须使用github
上的示例我刚刚复制了这段代码:
sigma.utils.pkg('sigma.canvas.nodes');
sigma.canvas.nodes.image = (function() {
var _cache = {},
_loading = {},
_callbacks = {};
// Return the renderer itself:
var renderer = function(node, context, settings) {
var args = arguments,
prefix = settings('prefix') || '',
size = node[prefix + 'size'],
color = node.color || settings('defaultNodeColor'),
url = node.url;
if (_cache[url]) {
context.save();
// Draw the clipping disc:
context.beginPath();
context.arc(
node[prefix + 'x'],
node[prefix + 'y'],
node[prefix + 'size'],
0,
Math.PI * 2,
true
);
context.closePath();
context.clip();
// Draw the image
context.drawImage(
_cache[url],
node[prefix + 'x'] - size,
node[prefix + 'y'] - size,
2 * size,
2 * size
);
// Quit the "clipping mode":
context.restore();
// Draw the border:
context.beginPath();
context.arc(
node[prefix + 'x'],
node[prefix + 'y'],
node[prefix + 'size'],
0,
Math.PI * 2,
true
);
context.lineWidth = size / 5;
context.strokeStyle = node.color || settings('defaultNodeColor');
context.stroke();
} else {
sigma.canvas.nodes.image.cache(url);
sigma.canvas.nodes.def.apply(
sigma.canvas.nodes,
args
);
}
};
// Let's add a public method to cache images, to make it possible to
// preload images before the initial rendering:
renderer.cache = function(url, callback) {
if (callback)
_callbacks[url] = callback;
if (_loading[url])
return;
var img = new Image();
img.onload = function() {
_loading[url] = false;
_cache[url] = img;
if (_callbacks[url]) {
_callbacks[url].call(this, img);
delete _callbacks[url];
}
};
_loading[url] = true;
img.src = url;
};
return renderer;
})();
并像这样实例化sigma(缓存图像):
images.forEach(function(url) {
sigma.canvas.nodes.image.cache(
url,
function() {
if (++loaded === images.length) {
s = new sigma({
graph: g,
renderer: {
// IMPORTANT:
// This works only with the canvas renderer, so the
// renderer type set as "canvas" is necessary here.
container: document.getElementById('graph-container'),
type: 'canvas'
},
settings: {
maxNodeSize: 20,
defaultLabelColor: '#fff',
labelColor: '#fff',
enableEdgeHovering: false
}
});
}
}
);
});
图像现在显示在节点上。