当我运行window.onload函数时,我得到意外的令牌非法

时间:2015-12-24 02:30:13

标签: javascript html5 canvas

请帮忙,当我运行Window.onload()=dank();函数时,收到错误消息,意外令牌非法。

<html>
<style>
</style>
<body background="background.jpg">
<canvas id="canvas" width="1300" height="630"></canvas>
<script>
var canvas=document.getElementById("canvas"); 
var ctx = canvas.getContext("2d");
var H=canvas.height;
var W=canvas.width;
var x=10; 
var y=15;
var rightPressed=false;
var leftPressed=false;
var upPressed=false;
var downPressed=false;
var heroX=20;
var heroY=20;
//this is where the error is

功能无法正常工作

Window.onload()=dank();
function dank(){
alert("How to play: move your hero using the arrow keys, and collect colored balls for powerups and points!
Get the highest score you can without touching a monster, which makes you    start over!
Collect the colored balls for more and better special powerups.");
}
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);

这是主要的游戏功能

function draw(){
ctx.clearRect(0, 0, canvas.width, canvas.height);
var heroImage=new Image();
heroImage.onload=function(){
ctx.drawImage(heroImage , heroX, heroY);
}
heroImage.src="hero.jpg";
dope();
}
function keyDownHandler(e) {
if(e.keyCode == 39) {
rightPressed = true;
}
else if(e.keyCode == 37) {
leftPressed = true;
}
else if(e.keyCode == 40) {
downPressed = true;
}
else if(e.keyCode == 38) {
upPressed = true;
}
}

function keyUpHandler(e) {
if(e.keyCode == 39) {
rightPressed = false;
}
else if(e.keyCode == 37) {
leftPressed = false;
}
else if(e.keyCode == 40) {
downPressed = false;
}
else if(e.keyCode == 38) {
upPressed = false;
}
}
function dope(){
if(rightPressed) {
heroX += 7;
}
else if(leftPressed) {
heroX -= 7;
}
else if(upPressed){
heroY -= 7
} 
else if(downPressed){
heroY +=7;
}
}
setInterval(draw, 10);
</script>
</body>
</html>

4 个答案:

答案 0 :(得分:1)

Javascript字符串不能跨越多行。

答案 1 :(得分:0)

试试这个而不是&#34; Window.onload()= dank();&#34;:

window.addEventListener('load',dank);

答案 2 :(得分:0)

不应该是:

Window.onload=dank();

function dank(){
    alert("How to play:");
}

答案 3 :(得分:0)

我试图执行不起作用的功能但只是遇到了一个问题 使用Window.onload()=dank()

我遇到了

Window.onload is not a function

所以我将其更改为Window.onload=dank()并且它正在运行。另外如前面的答案所指出的,javascript不能跨越多行。但您可以将警报文本更改为此

alert("How to play: move your hero using the arrow keys, and collect colored balls for powerups and points!" +
"Get the highest score you can without touching a monster, which makes you    start over!" +
"Collect the colored balls for more and better special powerups.")

WORKING MODEL