<p>所以我正在嘗試創建一個刮刮卡遊戲,用戶需要刮開卡片來揭示下面的內容。我想要檢查用戶是否刮開了畫布的70%來全部揭示。我正在嘗試使用phaser來實現這個功能,但是它不起作用。 </p>
<p>我嘗試計算imagedata以獲得像素數組,但它會傳回一個全為零的數組。我在下面的程式碼中使用了calculateScratchRatio函數。</p>
從「./BaseScene」匯入BaseScene;
const SKY_IMAGE = "天空";
const SKY_IMAGE_BLACK = "天黑";
const BOARD =「板」;
const HEADER_ACT = "header_act";
const KEY_BRUSH = "畫筆";
const BGGAME = "bg 遊戲";
匯出預設類別 Scratch 擴充功能 BaseScene {
構造函數(配置){
超級(“刮痕”,{...配置});
this.config = 配置;
this.isDown = false;
this.renderTexture = null;
this.brush = null;
this.erasedPixels = 0;
this.screenCenter = [config.width / 2, config.height / 2];
}
創造() {
超級.create();
this.cover = this.make.image({
鍵:SKY_IMAGE_BLACK,
添加:假,
});
this.board = this.make.image({
鍵盤,
添加:假,
});
this.ScratchOff();
this.add.image(...this.screenCenter, BOARD).setScale(0.7);
console.log(this.board.getBounds());
const headerinfo = this.add
.image(this.screenCenter[0] - 160, 130, "header_act")
.setScale(0.7);
讓 helloWorld = this.add
.text(0, 0, "你好世界")
.setFont("20px 宋體")
.setColor("#ffffff");
const 容器 = this.add.container(headerinfo.x, headerinfo.y);
容器.add(helloWorld);
}
刮掉(){
這個.add
.image(this.screenCenter[0] - 160, this.screenCenter[1], SKY_IMAGE)
.setScale(0.7);
this.cover.setOrigin(0, 0);
const 寬度 = this.cover.width;
const height = this.cover.height;
控制台.log(寬度,高度);
const rt = this.add.renderTexture(
this.screenCenter[0] - 160,
這個.screenCenter[1],
寬度*0.7,
高度*0.71
);
this.isRenderTextureErased = false;
this.erasureThreshold = 0.99;
rt.setOrigin(0.5, 0.5);
rt.draw(this.cover); //,寬度*0.5,高度*0.5)
rt.setInteractive();
rt.on(Phaser.Input.Events.POINTER_DOWN, this.handlePointerDown, this);
rt.on(Phaser.Input.Events.POINTER_MOVE, this.handlePointerMove, this);
rt.on(Phaser.Input.Events.POINTER_UP, () => (this.isDown = false));
this.brush = this.make.image({
鍵:KEY_BRUSH,
添加:假,
});
this.renderTexture = rt;
}
處理指針向下(指針){
this.isDown = true;
this.handlePointerMove(指針);
}
處理指針移動(指針){
if (!this.isDown) {
返回;
}
const x = 指標.x - this.renderTexture.x this.renderTexture.width * 0.5;
常數 y =
指標.y - this.renderTexture.y this.renderTexture.height * 0.5;
this.renderTexture.erase(this.brush, x, y);
const 結果 = this.calculateScratchRatio(x, y);
console.log(“結果”, 結果);
}計算刮痕比(x,y){
const 紋理 = this.textures.get(SKY_IMAGE_BLACK);
控制台.log(紋理);
如果(!紋理){
console.error(`未找到帶有鍵“${SKY_IMAGE_BLACK}”的紋理。`);
返回0;
}
控制台.log(紋理);
const canvas = document.createElement("canvas");
canvas.width =texture.source[0].width;
console.log("canvas.width", canvas.width);
canvas.height =texture.source[0].height;
const context = canvas.getContext("2d");
context.drawImage(texture.source[0].image, 0, 0);
const imageData = context.getImageData(0, 0, canvas.width, canvas.height);
const 像素 = imageData.data;
console.log(imageData, 像素);
讓擦除計數 = 0;
for (令 i = 3; i ></p>
你的程式碼中有很多內容,很難讓它正常運作。
最好的做法是發布一個迷你可運行程式碼,就像這裡提到的這裡。
不過,一個簡單快速的解決方案是使用
canvasTexture
來建立封面紋理,這樣你就可以直接從這個物件存取上下文。這是一個我會這樣做的簡短示範:
(基於這個答案的概念)