Pixi JS Graphics:在保持居中的同时调整圆的大小

Sir*_*bat 1 javascript geometry centering html5-canvas pixi.js

我正在尝试通过循环缩放方法来调整图形圆的大小。该循环将使圆的比例从 1 到 3,然后从 3 到 1 进行动画处理。下面的代码按照我的预期工作,但是,当圆放大时,它的大小会调整到右下角的方向。然后,在达到给定的最大比例后,圆的大小会调整回其相反方向(左上角)。这是代码:

const app = new PIXI.Application({
    width: 300,
    height: 300,
});

const canvasDiv = document.getElementById('canvasDiv');
canvasDiv.appendChild(app.view);

let circle = new PIXI.Graphics();
circle.beginFill(0xffffff);
circle.drawCircle(5, 5, 5);
circle.x = 150;
circle.y = 150;
circle.endFill();
app.stage.addChild(circle);

let scale = 1, motion = 1;

app.ticker.add(() => animateLoop());

function animateLoop(){
    if (motion == 1){
        if (scale < 3){
            scale += 0.2;
        }
        else{
            motion = 0;
        }
    }
    else{
        if (scale > 1){
            scale -= 0.2;
        }
        else{
            motion = 1;
        }
    }
    circle.scale.set(scale,scale);
}
Run Code Online (Sandbox Code Playgroud)

我读过 Pixi 网站并看到选项枢轴在调整大小期间处理图形的居中。我尝试实施它,它确实有一些微小的改进。然而,尽管尝试了多个枢轴值,但我无法精确地将圆居中。这是添加的代码:

/** On Motion 1 */
if (scale < 3){
    scale += 0.2;
    circle.pivot.x += 0.5;
    circle.pivot.y += 0.2;
}
/** On Motion 0 */
if (scale > 1){
    scale -= 0.2;
    circle.pivot.x -= 0.5;
    circle.pivot.y -= 0.2;
}
Run Code Online (Sandbox Code Playgroud)

我该如何解决?

obs*_*ure 5

枢轴点是对象局部坐标空间内的某个位置。

如果您看一下下图:

你可以看到左上角位于 x: 0 | y: 0 而右下角位于 x:circle.width | y:圆的高度。

这意味着如果我们想从圆心内缩放圆,我们需要将枢轴点移动到圆心!(x: 圆.宽度/2 | y: 圆.高度/2)

这是一个例子:

const app = new PIXI.Application({
  width: 400,
  height: 300,
  backgroundColor: 0x1099bb,
  resolution: window.devicePixelRatio || 1,
});
document.body.appendChild(app.view);

const container = new PIXI.Container();

let circle = new PIXI.Graphics();
circle.beginFill(0x00ffff);
circle.drawCircle(50, 50, 50);

circle.endFill();
circle.x = 200;
circle.y = 150;
circle.pivot.x = circle.width / 2;
circle.pivot.y = circle.height / 2;
app.stage.addChild(circle);

let scale = 1,
  motion = 1;

app.ticker.add(() => animateLoop());

function animateLoop() {
  if (motion == 1) {
    if (scale < 3) {
      scale += 0.1;
    } else {
      motion = 0;
    }
  } else {
    if (scale > 1) {
      scale -= 0.1;
    } else {
      motion = 1;
    }
  }
  circle.scale.set(scale, scale);
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://pixijs.download/release/pixi.js"></script>
Run Code Online (Sandbox Code Playgroud)