Created
February 11, 2019 19:14
-
-
Save shaefer/d805f41af6edda8a07d15003ce3e52ad to your computer and use it in GitHub Desktop.
Examples For Node Rendering with force-graph
This file contains 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
const simpleNodeAsText = (node, ctx) => { | |
ctx.font = '10px Sans-Serif'; | |
ctx.textAlign = 'center'; | |
ctx.textBaseline = 'middle'; | |
ctx.fillStyle = node.color; | |
ctx.fillText(node.id, node.x, node.y); | |
}; | |
const renderCircleWithLabel = (node, ctx, globalScale) => { | |
// Draw wider nodes by 1px on shadow canvas for more precise hovering (due to boundary anti-aliasing) | |
const padAmount = 1; | |
const nodRelSize = 4; | |
const r = Math.sqrt(Math.max(0, node.val || 1)) * nodRelSize + padAmount; | |
ctx.beginPath(); | |
ctx.arc(node.x, node.y, r, 0, 2 * Math.PI, false); | |
ctx.fillStyle = node.color || 'rgba(31, 120, 180, 0.92)'; | |
ctx.fill(); | |
ctx.textBaseline = 'middle'; | |
ctx.fillStyle = 'black'; | |
const fontSize = 12/globalScale; | |
ctx.font = `${fontSize}px Sans-Serif`; | |
ctx.fillText(node.id, node.x + (3 * globalScale), node.y); | |
} | |
const renderNodeAsRectangleWithText = (node, ctx, globalScale) => { | |
const label = node.id; | |
const fontSize = 12/globalScale; | |
ctx.font = `${fontSize}px Sans-Serif`; | |
const textWidth = ctx.measureText(label).width; | |
const bckgDimensions = [textWidth, fontSize].map(n => n + fontSize * 0.2); // some padding | |
ctx.fillStyle = '#000'; | |
ctx.lineWidth = 1; | |
ctx.strokeRect(node.x - bckgDimensions[0] / 2, node.y - bckgDimensions[1] / 2, ...bckgDimensions); | |
ctx.textAlign = 'left'; | |
ctx.textBaseline = 'middle'; | |
ctx.fillStyle = node.color; | |
ctx.fillText(label, node.x, node.y); | |
}; | |
const noHoverLabel = ''; | |
<ForceGraph2D graphData={data} nodeCanvasObject={renderCircleWithLabel} nodeAutoColorBy="group" nodeLabel={noHoverLabel} /> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment