简体   繁体   English

为什么在调用clearRect()之后不能写入画布?

[英]Why can't I write to a canvas after calling clearRect()?

I'm new to JavaScript and thought I would write a quiz for my nephews since they are really into star wars. 我是JavaScript的新手,并认为我会为我的侄子们写一个测验,因为他们真的很喜欢星球大战。 I've managed to do a 'title screen' and now want to write a pic and three possible answers to the screen. 我设法做了一个“标题屏幕”,现在想在屏幕上写一张图片和三个可能的答案。 But after clearing the screen on a mouseup call I can't seem to write anything to the canvas. 但是在通过mouseup调用清除屏幕后,我似乎无法在画布上写任何东西。 Here's my code: 这是我的代码:

<!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>

http://jsbin.com/koj/1/edit http://jsbin.com/koj/1/edit

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);
}

that's cause you need to call a function that will do something on click, not at the first runtime. 这是因为您需要调用一个函数,该函数将在单击时执行某些操作,而不是在第一次运行时执行。 So separate your functions, call them accordingly. 因此,分开您的功能,相应地调用它们。 You'll also probably need a counter, to know what's the next question and so on... 您可能还需要一个柜台,以了解下一个问题是什么,依此类推...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM