PIXI
一、基础
结合纸笔画图对照学习
我们正常用纸笔画图的步骤:
- 首先拿到一张纸
const app = new PIXI.Application();
- 放到桌子上
document.body.appendChild(app.view);
- 划分区域,比如:客厅、卫生间,并将划分的区域添加到纸上
const container = new PIXI.Container();
app.stage.addChild(container);
- 每块区域都有哪些东西,比如:客厅有桌子、椅子
var table = new PIXI.Graphics();
接下来,怎么画桌子?
4.1 填充色(桌面要涂成什么颜色)
// beginFill (color, alpha)
table.beginFill (0xFFFFFF, 1);
...
table.endFill();
4.2 线条样式(选笔:什么颜色、线条多粗、透明度等等样式)
// lineStyle (width, color, alpha, alignment, native)
table.lineStyle(1, 0xffffff);
4.3 从哪个位置开始
// moveTo (x, y)
table.moveTo(100, 100);
4.4 什么形状,画到哪里为止(直线、圆等等)
// 直线,从moveTo的位置到lineTo的位置的一条直线
// lineTo (x, y)
table.lineTo(200, 100)
// 圆,
// arc (cx, cy, radius, startAngle, endAngle, anticlockwise)
table.arc(200, 100, 50, 0, Math.PI * 2, true);
或
// drawCircle (x, y, radius)
table.drawCircle (200, 100, 50);
// 方形
// drawRect (x, y, width, height)
table.drawRect (100, 100, 50, 50);
4.5 上边画完了,我想再重新再起一个位置,画另一个图形(提起笔,放到下一个目标位置,画下一个桌子)
table.moveTo(300, 300).lineTo(200, 100, 50, 0, Math.PI * 2, true);
- 桌子、椅子拿到后要放入对应区域(客厅)
container.addChild(table);
- 区域的位置默认是(0, 0),也可以调整
container.position.set(100, 100);
或
container.x = 100;
container.y = 100;
- 区域旋转
// 先选择支点(此处以中心点为支点)
container.pivot.x = container.width / 2;
container.pivot.y = container.height / 2;
// 旋转
container.rotation = Math.PI;
- 添加贴图
const rootIconTexture = PIXI.Texture.from(require('@static/images/robot.png'));
const rootIcon = PIXI.Sprite.from(rootIconTexture);
rootIcon.anchor.set(0.5); // 已中心为原点
rootIcon.scale.set(0.5); // 缩小50%
- 添加标题
const label = new PIXI.Text(opt.label);
label.style.fontFamily = "Arial";
nodeContainer.addChild(label);
- 添加动画
app.ticker.add((delta) => {
container.rotation -= 0.01 * delta;
});
二、 进阶
实际项目中遇到的问题:放射性箭头线怎么画? 先看下效果图:
思路:先画线,在画箭头,然后再调整角度
const start = {
x: 10,
y: 20,
}
const end = {
x: 120,
y: 130,
}
const line = new PIXI.Graphics();
// 设置线条样式
line.lineStyle(config.lineWidth, config.lineColor);
// 找到起点
line.moveTo(start.x, start.y);
// 计算线条的长度
const distance = getDistance(start, end);
// 先横着画
line.lineTo(start.x + distance, start.y);
line.closePath();
// 画箭头
const arrowStart = {
x: start.x + distance,
y: start.y,
}
line.beginFill(lineColor);
line.moveTo(arrowStart,x, arrowStart.y);
line.lineTo(arrowStart.x - 6, arrowStart.y - 4); // 这里箭头的大小依需求而定
line.lineTo(arrowStart.x - 6, arrowStart.y + 4);
line.lineTo(arrowStart.x, arrowStart.y);
line.endFill();
// 定位
line.position.x = start.x;
line.position.y = start.y;
// 设置旋转支点
line.pivot.x = start.x;
line.pivot.y = start.y;
// 调整角度
line.rotation = angle(start, end);
// 勾股定理获取两点间距离
getDistance(start, end) {
const x = end.x - start.x;
const y = end.y - start.y;
return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
}
// 角度
angle(start, end) {
var diffX = end.x - start.x,
diffY = end.y - start.y;
return Math.atan2(diffY, diffX);
}