I'm trying to resize a graphic circle by looping the scale method. The loop will animate the circle's scale from 1 to 3 then 3 to 1. The code below works as I intended it to however, when the circle enlarges, it resizes to the direction of bottom-right. Then, the circle resizes back to its opposite direction (top-left) after reaching the given max scale. Here's the code:
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);
}
I've read the Pixi site and saw the option pivot to handle the centering of the graphics during resizing. I tried impementing it, and it does have slight improvements. However, I'm not able to exactly center the circle despite trying multiple pivot values. Here's the added code:
/** 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;
}
How do I fix this?
The pivot point is a location somwhere inside an object's local coordinate space.
If you take a look at the following illustration:
you can see that the top-left corner is at x: 0 | y: 0 while the lower-right is at x: circle.width | y: circle.height.
That means if we want to scale the circle from within it's center we need to move the pivot point to the center of it! (x: circle.width/2 | y: circle.height/2)
Here's an example:
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);
}
<script src="https://pixijs.download/release/pixi.js"></script>