将先前保存的画布的getImageData添加到其他图像之上



我试图用一个图像覆盖整个画布,同时让它有一个透明的洞。

基本上我有一个玩家的游戏。我想用一个图像覆盖整个游戏,除了玩家的位置。当我考虑用颜色填充选项,但我想用图像填充时,这很好。以下是我的(失败的(代码:

var img = new Image();
img.onload = function() {
ctx.clearRect(0, 0, width, height);
drawMap(); // draws my "hidden game"
ctx.beginPath();
ctx.fillStyle = visionRadial(game.p1.px, game.p1.py);
ctx.rect(game.p1.px - 50, game.p1.py - 50, 100, 100);
ctx.fill(); // this gives me a transparent circle around the position of the player.
// Trying to save the image around my player
var p1 = ctx.getImageData(game.p1.px - 50, game.p1.py - 50, 100, 100);
// Image to cover the board game
ctx.drawImage(img, 0, 0);
// Adding back the player position (transparent lens)
ctx.putImageData(p1, game.p1.px - 50, game.p1.py - 50);
};
img.src = 'example.jpg';

但这并不奏效。似乎当我在p1中保存前一张图像的部分时,该图像不再显示。。。

我在这里错过了什么?

非常感谢!

画布,可绘制的图像

函数CCD_ 1和CCD_。使用像素数据进行渲染非常缓慢,因为像素数据不是由GPU渲染的,不能进行透明、过滤、合成、缩放等操作。作为渲染源几乎毫无用处

与其将图像存储为像素数据,不如创建第二个画布,在上面绘制您需要的内容,并将其用作具有完全硬件支持和所有其他图像功能的图像。

示例

修改代码以使用画布来放置覆盖。

// creates a canvas, size w, h , and copies canvasToCopy onto it at x, y 
function createOverlay(canvasToCopy, x, y, w, h) {
const overlay = document.createElement("canvas");
overlay.width = w;
overlay.height = h;
const ctx = overlay.getContext("2d");
ctx.drawImage(canvasToCopy, -x, -y);  // copies canvas to overlay
return overlay;
}
var overlay; // to hold overlay image (a canvas)
var img = new Image();
img.src = "example.jpg";
img.onload = () => {
ctx.clearRect(0, 0, width, height);
drawMap(); 
ctx.beginPath();
ctx.fillStyle = visionRadial(game.p1.px, game.p1.py);
ctx.rect(game.p1.px - 50, game.p1.py - 50, 100, 100);
ctx.fill(); 
// copy current canvas content to overlay
overlay = createOverlay(ctx.canvas, game.p1.px - 50, game.p1.py - 50, 100, 100);
ctx.drawImage(img, 0, 0);
// draw overlay over canvas content
ctx.drawImage(overlay, game.p1.px - 50, game.p1.py - 50);
img.onload = undefined; // never leave an onload (any unused event) set once done
// De-reference so resources closed over can be set free
};

最新更新