Skip to content

Instantly share code, notes, and snippets.

@colinfwren
Created September 1, 2024 22:35
Show Gist options
  • Save colinfwren/0fe9923ebac935f15fc58893be01d876 to your computer and use it in GitHub Desktop.
Save colinfwren/0fe9923ebac935f15fc58893be01d876 to your computer and use it in GitHub Desktop.
function nodeCanvasObject(node, ctx, globalScale) {
const nodeColour = 'red'
const fontSize = 12/globalScale;
ctx.font = `${fontSize}px Sans-Serif`;
const textWidth = ctx.measureText(node.name).width;
const bckgDimensions = [textWidth, fontSize].map(n => n + fontSize * 0.2); // some padding
// node circle
ctx.fillStyle = 'red'
ctx.beginPath()
ctx.arc(node.x, node.y, 5, 0, 2 * Math.PI, false)
ctx.fill()
// label background
ctx.fillStyle = 'rgba(255, 255, 255, 0.8)';
ctx.fillRect(node.x - bckgDimensions[0] / 2, (node.y + 10) - bckgDimensions[1] / 2, ...bckgDimensions);
ctx.fillStyle = 'red'
ctx.textAlign = 'center'
ctx.textBaseline = 'middle'
ctx.fillText(node.name, node.x, node.y + 10)
node.__bckgDimensions = bckgDimensions; // to re-use in nodePointerAreaPaint
}
function nodePointerAreaPaint(node, color, ctx) {
ctx.fillStyle = color;
const bckgDimensions = node.__bckgDimensions;
bckgDimensions && ctx.fillRect(node.x - bckgDimensions[0] / 2, (node.y - 20) - bckgDimensions[1] / 2, ...bckgDimensions);
}
ReactDOM.render(
<ForceGraph2D
graphData={data}
nodeCanvasObject={nodeCanvasObject}
nodePointerAreaPaint={nodePointerAreaPaint}
/>,
document.getElementById('graph')
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment