我目前正在开发一款游戏,但我偶然发现了一个问题,即 fillRect() 命令无法使用 Javascript 在 HTML5 Canvas 上运行。在尝试对其进行研究并检查我的代码之后,我不知道为什么会这样。 HTML代码如下所示:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Cube Quest</title>
<style>
#game {
border: 1px dashed black;
}
</style>
</head>
<body>
<canvas id="game" width='1280' height='720'>Your browser does not support the canvas element in HTML5.</canvas>
<script>
var clicked = false; // Mouse handling event
var mouseX = event.cilentX; // Mouse X coordinate
var mouseY = event.cilentY; // Mouse Y coordinate
var canvas = document.getElementById("game"); // For canvas
var ctx = canvas.getContext("2d"); // For canvas
ctx.fillStyle = 'black'; // rectangle color selection
ctx.fillRect(10, 10, 150, 80);
</script>
</body>
</html>
我不是最好的 Javascript 专家,所以我知道的很少,这可以帮助我理解代码正确时没有矩形显示的原因。
非常感谢您提前就此特定问题提供的帮助。 :)
最佳答案
您需要查看 JS 中的 addEventListener 函数以更好地了解情况。 这里的工作示例:
// globals
var canvas = document.getElementById("game");
var clicked = false; // Mouse handling event
var mouseX = 0;
var mouseY = 0;
// yuor application parameters
var app = {
clearCanvas: true,
title: 'HELLO'
};
canvas.addEventListener('click' , function (event){
mouseX = event.pageX; // Mouse X coordinate
mouseY = event.pageY; // Mouse Y coordinate
console.log("Mouse x : " + mouseX + " Mouse y :" + mouseY );
drawAgain();
});
// Initial draw
var ctx = canvas.getContext("2d"); // For canvas
ctx.fillStyle = 'black'; // rectangle color selection
ctx.fillRect(mouseX, mouseY, 350, 65);
ctx.font="30px Arial";
ctx.fillStyle = 'lime';
ctx.fillText(app.title + "X:" + mouseX + " Y:" + mouseY , mouseX + 35, mouseY + 40, 250)
// Draw when you need
function drawAgain () {
if (app.clearCanvas == true){
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
ctx.fillStyle = 'black'; // rectangle color selection
ctx.fillRect(mouseX, mouseY, 350, 65);
ctx.fillStyle = 'lime';
ctx.fillText(app.title + " X:" + mouseX + " Y:" + mouseY , mouseX + 35, mouseY + 40, 400)
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Cube Quest</title>
<style>
#game {
border: 1px dashed black;
}
</style>
</head>
<body>
<canvas id="game" width='1280' height='720'>Your browser does not support the canvas element in HTML5.</canvas>
<script>
</script>
</body>
</html>
Suggestion: Also learn to use removeEventListener , lot of web developers have trouble with event conflict situation when they use lot of lib's. For dynamic app flow methodology use removeEventListener before setting a flags.
关于javascript - Javascript 中的命令 fillRect() 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50246748/