gpt4 book ai didi

javascript - 如何绘制箭头以通过 ngraph.pixi 与 PIXI.js 与 webgl 链接?

转载 作者:行者123 更新时间:2023-12-02 22:41:57 30 4
gpt4 key购买 nike

我画了直接图,所以我画了线的箭头,我是 pixi.js 和 javascript 的新手,我想学习它,你能帮助我如何画一个箭头吗是吗?

这是一个demo我想将箭头添加到链接。

这是绘制链接的代码,位于 this class

module.exports = function (link, ctx) {
ctx.lineStyle(link.width, 0x333333, 1);
ctx.moveTo(link.from.x, link.from.y);
ctx.lineTo(link.to.x, link.to.y);
}

这是完整的代码

module.exports.main = function () {
var graph = require('ngraph.generators').balancedBinTree(5);
var createPixiGraphics = require('../');

var setting = {
rendererOptions: {
backgroundColor: 0xFFFFFF,
antialias: true,
}
}

var pixiGraphics = createPixiGraphics(graph, setting);
pixiGraphics.createLinkUI(require('./lib/createLinkUI'));
pixiGraphics.renderLink(require('./lib/renderLink'));
pixiGraphics.createNodeUI(require('./lib/createNodeUI'));
pixiGraphics.renderNode(require('./lib/renderNode'));
var layout = pixiGraphics.layout;

// just make sure first node does not move:
layout.pinNode(graph.getNode(1), true);

// begin animation loop:
pixiGraphics.run();
}

复制代码的链接是here

非常感谢

最佳答案

据我所知,pixi.js 不支持开箱即用的箭头渲染。您必须手动绘制箭头。这个想法是使用原始向量运算来计算箭头翅膀应该在哪里。

如果使用归一化向量(长度等于1的向量)进行操作会更容易实现。一旦你有了图形链接的向量,你就知道了它的方向,然后你就可以计算链接上的偏移量,箭头翼应该停在哪里。一旦偏移,您所要做的就是获取一个正交向量并从原始向量向左/向右移动 - 这些是您的箭翼应该停止的点。

如果画个图就更容易理解了,但是我现在没有好的钢笔和铅笔,所以这里是渲染箭头的代码:

function defaultLinkRenderer(link) {
graphics.lineStyle(1, 0xcccccc, 1);
graphics.moveTo(link.from.x, link.from.y);
graphics.lineTo(link.to.x, link.to.y);

// first, let's compute normalized vector for our link:
let dx = link.to.x - link.from.x;
let dy = link.to.y - link.from.y;
let l = Math.sqrt(dx * dx + dy * dy);

if (l === 0) return; // if length is 0 - can't render arrows

// This is our normal vector. It describes direction of the graph
// link, and has length == 1:
let nx = dx/l; let ny = dy/l;

// Now let's draw the arrow:
let arrowLength = 6; // Length of the arrow
let arrowWingsLength = 2; // How far arrow wings are from the link?

// This is where arrow should end. We do `(l - NODE_WIDTH)` to
// make sure it ends before the node UI element.
let ex = link.from.x + nx * (l - NODE_WIDTH);
let ey = link.from.y + ny * (l - NODE_WIDTH);

// Offset on the graph link, where arrow wings should be
let sx = link.from.x + nx * (l - NODE_WIDTH - arrowLength);
let sy = link.from.y + ny * (l - NODE_WIDTH - arrowLength);

// orthogonal vector to the link vector is easy to compute:
let topX = -ny;
let topY = nx;

// Let's draw the arrow:
graphics.moveTo(ex, ey);
graphics.lineTo(sx + topX * arrowWingsLength, sy + topY * arrowWingsLength);
graphics.moveTo(ex, ey);
graphics.lineTo(sx - topX * arrowWingsLength, sy - topY * arrowWingsLength);
}

这会呈现出漂亮的箭头:

final result

关于javascript - 如何绘制箭头以通过 ngraph.pixi 与 PIXI.js 与 webgl 链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58563989/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com