作成中のゲームの背景に多数の光源を配置したいと考えています。以下に示すように、1 つの光源でうまく機能します。
これは、次のように、.png 画像を他のすべての上に配置することで実現されます。
1 つの光源にはうまく機能しますが、光源を追加して移動できる別のアプローチが必要です。
フレームごとに同様の「シャドウレイヤー」をピクセルごとに描画することを検討し、各光源までの距離に応じて透明度を計算しました。ただし、それはおそらく非常に遅くなり、この問題にはもっと良い解決策があると確信しています。
画像は単なる例であり、各フレームには、requestAnimationFrame を使用して移動および更新するかなり多くのコンテンツがあります。
これを達成するための軽量で簡単な方法はありますか?前もって感謝します!
編集
ViliusL の助けを借りて、このマスキング ソリューションを思いつきました。
// Create canvas
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
canvas.width = 300;
canvas.height = 300;
document.body.appendChild(canvas);
// Draw background
var img=document.getElementById("cat");
ctx.drawImage(img,0,0);
// Create shadow canvas
var shadowCanvas = document.createElement('canvas');
var shadowCtx = shadowCanvas.getContext('2d');
shadowCanvas.width = canvas.width;
shadowCanvas.height = canvas.height;
document.body.appendChild(shadowCanvas);
// Make it black
shadowCtx.fillStyle= '#000';
shadowCtx.fillRect(0,0,canvas.width,canvas.height);
// Turn canvas into mask
shadowCtx.globalCompositeOperation = "destination-out";
// RadialGradient as light source #1
gradient = shadowCtx.createRadialGradient(80, 150, 0, 80, 150, 50);
gradient.addColorStop(0, "rgba(255, 255, 255, 1.0)");
gradient.addColorStop(1, "rgba(255, 255, 255, .1)");
shadowCtx.fillStyle = gradient;
shadowCtx.fillRect(0, 0, canvas.width, canvas.height);
// RadialGradient as light source #2
gradient = shadowCtx.createRadialGradient(220, 150, 0, 220, 150, 50);
gradient.addColorStop(0, "rgba(255, 255, 255, 1.0)");
gradient.addColorStop(1, "rgba(255, 255, 255, .1)");
shadowCtx.fillStyle = gradient;
shadowCtx.fillRect(0, 0, canvas.width, canvas.height);