我是 JavaScript 新手,我想为我的侄子们写一个测验,因为他们真的很喜欢星球大战。我已经成功制作了一个“标题屏幕”,现在想在屏幕上写一张图片和三个可能的答案。但是在 mouseup
调用上清除屏幕后,我似乎无法在 Canvas 上写入任何内容。这是我的代码:
<!DOCTYPE html>
<html>
<head>
<title> star wars </title>
</head>
<body>
<canvas id="myCanvas" width="1400" height="700" style="border:2px solid black"></canvas>
<script type="text/javascript">
//print intro screen
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
var pic = new Image();
pic.onload = function(){
ctx.drawImage(pic, 0,0);
}
pic.src="http://i.imgur.com/wZHhlqt.png";
canvas.onmouseup = function(){
ctx.clearRect(0, 0, 1400, 700);
}
ctx.font = '40pt Calibri';
ctx.fillStyle = 'blue';
ctx.fillText("Question 1 ", 140, 440);
</script>
</body>
</html>
最佳答案
canvas.onmouseup = function(){
ctx.clearRect(0, 0, 1400, 700);
q1();
}
function q1(){
ctx.font = '40pt Calibri';
ctx.fillStyle = 'blue';
ctx.fillText("Question 1 ", 140, 440);
}
这是因为您需要调用一个函数,该函数将在单击时而不是在第一次运行时执行某些操作。因此,将您的函数分开,并相应地调用它们。 您可能还需要一个计数器,以知道下一个问题是什么等等......
关于javascript - 为什么调用clearRect()后无法写入 Canvas ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21811104/