简体   繁体   中英

HTML5 Canvas not displaying in browser

I'm following this tutorial to learn HTML5 game development using javascript and jQuery. However, I've already come across a problem. When I run the HTML page that my js file is referenced from, nothing loads, and is just a blank screen. Here is the code for both files. Note that I haven't gotten very far in the tutorial.

index.html

<HTML>
<head>
</head>
<body>
<p>HTML5 and jQuery Tests</p>
<script type ="text/javascript" src="test.js"></script>
</body>
</HTML>

test.js

var CANVAS_WIDTH = 480;
var CANVAS_HEIGHT = 320;

var canvasElement = $("<canvas width='" + CANVAS_WIDTH +"' height='" + CANVAS_HEIGHT +        "'></canvas>");
var canvas = canvasElement.get(0).getContext("2d");
canvasElement.appendTo('body');
var FPS = 30;
setInterval(function() {
update();
draw();
}, 1000/FPS);
function draw() {
canvas.fillStyle = "#000"; 
canvas.fillText("hello.", 50, 50);
}

Any help would be greatly appreciated! Also, am I allowed to ask questions about this code in this forum, on the same thread, or do I have to stat another?

Thanks! ~Carpetfizz

You don't have an update function to call. When the setInterval fires (which is ~32ms after the script loads), you're getting an error.

You need to add jQuery.
It's a library that was written to make working with HTML easier.
It needs to exist above where test.js does.

You can either download your own copy of it, or link to a copy elsewhere on the net - both will work fine.

$ is used by jQuery as a function to intelligently grab different kinds of items: HTML, JS, etc, and return JS objects with helpful functions for working with whatever you asked for.

Anyway, the update would still have caused an error, it was just second in line, behind the missing script.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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