Last active
April 27, 2022 16:04
-
-
Save r3code/a7dee112cdccad1e79476ff60973bd81 to your computer and use it in GitHub Desktop.
vis.js draw custom image for node shape square or box
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://codepen.io/anon/pen/mjJMOy | |
<div id="graph"></div> | |
<script> | |
document.addEventListener('DOMContentLoaded', function() { | |
document.addEventListener('DOMContentLoaded', function() { | |
var container = document.querySelector('#graph'); | |
var data = { | |
nodes: [ | |
{ | |
id: 1, | |
shape: 'square', | |
image: 'https://lenguajehtml.com/img/html5-logo.png', | |
label: 'HTML5', | |
borderWidth: 1, | |
border: 'orange', | |
borderWidthSelected: 1, | |
color: { | |
background: 'Green', | |
border: 'Green', | |
highlight: { | |
background: 'pink', | |
border: 'black' | |
} | |
}, | |
}, | |
{ | |
id: 2, | |
shape: 'square', | |
image: 'https://lenguajecss.com/img/css3-logo.png', | |
label: 'CSS3', | |
color: 'red', | |
}, | |
], | |
edges: [ | |
{from: 1, to: 2}, | |
] | |
} | |
var options = { | |
nodes: { | |
borderWidth:0, | |
size:42, | |
color: { | |
border: '#222', | |
background: 'transparent' | |
}, | |
font: { | |
color: '#111', | |
face: 'Walter Turncoat', | |
size: 16, | |
strokeWidth: 1, | |
strokeColor: '#222' | |
} | |
}, | |
edges: { | |
color: { | |
color: '#CCC', | |
highlight: '#A22' | |
}, | |
width: 3, | |
length: 275, | |
hoverWidth: .05 | |
} | |
} | |
var network = new vis.Network(container, data, options); | |
var bgObj = new Image(); | |
bgObj.onload = function() { | |
}; | |
bgObj.src = 'http://upload.turkcewiki.org/wikipedia/commons/thumb/d/de/Blank_map_of_Russia-gray.svg/800px-Blank_map_of_Russia-gray.svg.png'; | |
network.on("beforeDrawing", function (ctx) { | |
ctx.drawImage(bgObj, -bgObj.width/4, -bgObj.height/4, bgObj.width/2,bgObj.height/2); | |
}); | |
// Рисование картинки на нодах в Vis.JS | |
// TODO: картинки нужно закшировать в списке, чтобы при перерисовке их | |
// не запрашивать с сервера, а брать из объекта в кеше | |
// Для справки см. lib\network\CachedImage.js | |
var imageObj = new Image(); | |
imageObj.onload = function() { | |
}; | |
imageObj.src = 'https://www.html5canvastutorials.com/demos/assets/darth-vader.jpg'; | |
network.on("afterDrawing", function (ctx) { | |
var nodeId = 1; | |
var nodePositions = network.getPositions([nodeId]); | |
var x = nodePositions[nodeId].x; | |
var y = nodePositions[nodeId].y; | |
var imageSize = 64; | |
ctx.drawImage(imageObj, x-imageSize/2, y-imageSize/2, imageSize,imageSize); | |
}); | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment