P粉2074830872023-08-15 19:19:20
There's a lot in your code and it's hard to get it to work.
The best thing to do is to publish a mini runnable code like mentioned herehere.
However, a simple and quick solution is to use canvasTexture
to create the cover texture so that you can access the context directly from this object.
Here is a short demonstration of how I would do it:
(Based on the concept of this answer)
document.body.style = 'margin:0;'; class ScratchScene extends Phaser.Scene { constructor() { super('ScratchScene') } create(){ let helperGraphics = this.make.graphics({x:0, y: 0, add: false}); helperGraphics.fillStyle(0xff0000); helperGraphics.fillRect(0, 0, 200, 50 ); helperGraphics.generateTexture('cover', 200, 50); let coverImage = this.textures.get('cover').getSourceImage() this.coverHelperCanvas = this.textures.createCanvas('coverTexture', 200, 50) this.coverHelperCanvas.draw(0, 0, coverImage) this.coverHelperCanvas.context.globalCompositeOperation = 'destination-out' this.precent = this.add.text(10 , 10, '' ); this.add.text( config.width/2, config.height / 2, 'YOU WON') .setOrigin(.5) .setFontSize(20); let cover = this.add.image(config.width/2, config.height / 2, 'coverTexture') .setInteractive(); cover.on('pointermove', this.clearCover, this); this.checkPercent(); } checkPercent(){ let full = 200 * 50; let { data } = this.coverHelperCanvas.context.getImageData(0, 0,200, 50); let current = data.filter((v,i) => ((i + 1) % 4 == 0) && v > 0).length; this.precent.setText(`Cover Percent: ${ (current / full * 100).toFixed(2) }%` ); } clearCover(e, x, y){ let radius = 10; this.coverHelperCanvas.context.beginPath() this.coverHelperCanvas.context.arc(x, y, radius, 0, Math.PI * 2, false) this.coverHelperCanvas.context.fill(); this.coverHelperCanvas.update(); this.checkPercent(); } } var config = { type: Phaser.AUTO, width: 536, height: 163, scene: [ScratchScene] }; new Phaser.Game(config); console.clear();
<script src="https://cdn.jsdelivr.net/npm/phaser/dist/phaser.min.js"></script>