我正在使用 JavaScript 创建基于像素的黑暗模拟灯光,以提高我的编码技能。目标是在光标移动时在光标周围创建一个光泡。我只渲染光标周围的一小部分以确保实时结果。我尝试创建尽可能可扩展和友好的代码,甚至可以自定义光标的光线和像素的分辨率。这是我的代码:
var Canvas = {
Element: document.createElement("canvas"),
Width: 500,
Height: 500,
Style: "border: 1px solid black;",
Resolution: 10,
Matrix: [],
Context: null,
};
var Light = {
Intensity: 20
}
document.body.appendChild(Canvas.Element);
Canvas.Element.style = Canvas.Style;
Canvas.Element.width = Canvas.Width;
Canvas.Element.height = Canvas.Height;
Canvas.Matrix = new Array(Canvas.Height / Canvas.Resolution).fill().map(() => new Array(Canvas.Width / Canvas.Resolution).fill({Intensity: 0}));
console.log(Canvas.Matrix);
Canvas.Context = Canvas.Element.getContext("2d");
Canvas.Element.addEventListener('mousemove', function(event){
var Rect = Canvas.Element.getBoundingClientRect();
var Mouse = {
X: event.clientX - Rect.left,
Y: event.clientY - Rect.top,
}
Canvas.Context.fillRect(0, 0, Canvas.Width, Canvas.Height);
Canvas.Context.clearRect(Mouse.X - (Light.Intensity / 2) * Canvas.Resolution, Mouse.Y - (Light.Intensity / 2) * Canvas.Resolution, Light.Intensity * Canvas.Resolution, Light.Intensity * Canvas.Resolution)
for(var x = Mouse.X / Canvas.Resolution - (Light.Intensity / 2); x < Mouse.X / Canvas.Resolution + (Light.Intensity / 2); x++){
for(var y = Mouse.Y / Canvas.Resolution - (Light.Intensity / 2); y < Mouse.Y / Canvas.Resolution + (Light.Intensity / 2); y++){
if(x || y <= 0){
CellDistance = Math.sqrt(Math.pow(Mouse.X - (Light.Intensity / 2), 2) + Math.pow(Mouse.X - (Light.Intensity / 2), 2));
Canvas.Matrix[x][y].Intensity = CellDistance
}
}
}
});
<html>
</html>
如您所见,我收到以下错误:
Uncaught TypeError: Cannot read properties of
undefined
我确信在浏览这段代码时我已经失去了脑细胞,因为我确信我已经定义了 Canvas.Matrix。我对编码相当陌生,这可能是一个愚蠢的错误。任何帮助都是有帮助的。谢谢!
这是因为您的
Canvas.Matrix
对象仅包含整数(0、1、...、50),但您的 x
和 y
是实数(9.1、6.7 等)。
因此,您必须先使用
x
或 y
或 Math.floor
来铺设地板或天花板 Math.ceil
和 Math.round
。 Math.floor
向下舍入,Math.ceil
向上舍入,Math.round
根据除法模数向上或向下舍入