<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>vis.js Custom Shape Example</title><scripttype="text/javascript"src="https://unpkg.com/vis-network/standalone/umd/vis-network.min.js"></script><styletype="text/css">#mynetwork{width:600px;height:400px;border:1pxsolidlightgray;}</style></head><body><divid="mynetwork"></div><script>functioncustomShapeRenderer({ctx,x,y,state:{selected,hover},style}){constr=style.size;// size of the shape (radius)ctx.beginPath();constsides=6;// number of sides for the hexagonconsta=(Math.PI*2)/sides;// angle between sides// Start drawing the hexagonctx.moveTo(x+r*Math.sin(0),y+r*Math.cos(0));for(leti=1;i<=sides;i++){ctx.lineTo(x+r*Math.sin(a*i),y+r*Math.cos(a*i));}ctx.closePath();ctx.save();ctx.fillStyle=selected?'blue':'red';// change color if selectedctx.fill();ctx.strokeStyle=hover?'orange':'black';// change stroke if hoveredctx.stroke();ctx.restore();// Add label inside the shapectx.font="normal 12px sans-serif";ctx.fillStyle='black';ctx.fillText('Custom Node',x-r/2,y+4);// Return dimensions of the nodereturn{nodeDimensions:{width:r*2,height:r*2}};}// Create nodes and edgesconstnodes=newvis.DataSet([{id:1,label:'Custom Node',shape:'custom',ctxRenderer:customShapeRenderer,// specify the custom renderersize:40// set the size of the node}]);constedges=newvis.DataSet([]);// Create the networkconstcontainer=document.getElementById('mynetwork');constdata={nodes:nodes,edges:edges};constoptions={};constnetwork=newvis.Network(container,data,options);</script></body></html>
Explanation:
Custom Renderer (customShapeRenderer): This function creates a hexagonal node. It takes the context (ctx) and node state as input, calculates the position of each side of the hexagon, and draws the shape using the canvas API.
The node is filled with red unless it is selected, in which case it becomes blue.
The stroke color is black but changes to orange when the node is hovered over.
The label "Custom Node" is drawn inside the hexagon.
Node Configuration: The node uses the shape: 'custom' property to specify that it should use a custom renderer. The ctxRenderer property is set to the customShapeRenderer function.
Node Dimensions: The size of the hexagonal node is defined by the r variable, which is passed in via style.size.
When you load this HTML file in a browser, it will draw a single hexagonal node with the ability to change color when selected or hovered. You can easily modify the shape or style further by changing the drawing logic inside the customShapeRenderer function.