我希望在用鼠标单击画布的地方出现一个红色方块,但是当我单击该方块时,我很难让该正方形出现在画布上。函数start包含window.addEventListener(),应该在mouseclick上创建一个组件,但是我不确定是否丢失了某些东西,或者只是完全错了。
<!DOCTYPE html>
<html>
<head>
<meta = name="viewport" content="width=device-width, initial-scale=1.0"/>
<style>
canvas {
border:1px solid #d3d3d3;
background-color: #f1f1f1;
}
</style>
</head>
<body onload="start() {
gameArea.start();
}
var gameArea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 840;
this.canvas.height = 540;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
//I don't know what Im doing wrong here
window.addEventListener('mousedown', function (e) {
new component(30, 30, "red", 10, 120);
})
}
}
//and here
function component(width, height, color, x, y) {
this.width = width;
this.height = height;
this.x = x;
this.y = y;
}
</script>
</html>
答案 0 :(得分:0)
window.addEventListener('mousedown', (e) => {
const {layerX, layerY} = e;
const rectSize = 30;
this.context.fillStyle = 'red';
this.context.fillRect(layerX - rectSize / 2, layerY - rectSize / 2, rectSize, rectSize);
});
您传递了一个函数(){},该函数没有您的gameArea
的上下文。另一部分是画布API。