admin管理员组

文章数量:1309940

I need to be able to click on background, and get the position of the click.

I tried adding an event listener to stage like this

app.stage.interactive = true;
app.stage.on('click', function(){
    console.log('hello');
})

I need to be able to click on background, and get the position of the click.

I tried adding an event listener to stage like this

app.stage.interactive = true;
app.stage.on('click', function(){
    console.log('hello');
})

but it works only if i click on element inside the stage, not the background itself.

Do i need to make a sprite as a background, if so, how do i set its background color and make sure it stays under all the other elements?

Share Improve this question asked Jul 10, 2020 at 13:21 MaksimMaksim 991 silver badge7 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

The stage is a PIXI.Container, which means it's basically an empty node that can hold children. It doesn't have dimensions of its own, and so when the interaction manager goes to hit-test your click, it isn't detected.

Your suggestion of adding a background sprite is probably the simplest solution. You can add one like so:

// Create the background sprite with a basic white texture
let bg = new PIXI.Sprite(PIXI.Texture.WHITE);
// Set it to fill the screen
bg.width = app.screen.width;
bg.height = app.screen.height;
// Tint it to whatever color you want, here red
bg.tint = 0xff0000;
// Add a click handler
bg.interactive = true;
bg.on('click', function(){
  console.log('hello');
});
// Add it to the stage as the first object
app.stage.addChild(bg);

// Now add anything else you want on your stage
...

PixiJS renders objects in order, so if you add your background sprite as the first child of the app's stage, it will be rendered behind all other content. When hit-testing a click, it will be the last object tested, and so will catch a click on the background of the stage. Note that to "block" clicks, other objects will need to be set to interactive = true, even if they don't have a click handler attached!

A possible solution would be to add an event on app's view.

app.renderer.view.addEventListener('click', function(e) {
  console.log(e);
});

本文标签: javascriptPixi jsneed to make clickable backgroundStack Overflow