I'm very new to JS with HTML5, and I cannot get a very basic piece of code to work. I have made the canvas, appended it to the body, and tried to write text, but nothing shows up.
<!doctype html>
<html lang="en">
<head>
<meta charset='utf-8'>
<title>Test Game</title>
</head>
<body>
<script type="text/javascript">
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');
</script>
<script type="text/javascript">
var FPS = 30;
setInterval(function(){
update();
draw();
},1000/FPS);
function update(){
}
function draw(){
canvas.fillStyle = "#000";//Sets colour to black
canvas.fillText("Sup Bro!",50,50);
}
</script>
</body>
</html>
You haven't included the jQuery core script before, which is why it is failing. Also, I'd recommend using jQuery functions to add attributes instead, rather than using strings.
<!doctype html>
<html lang="en">
<head>
<meta charset='utf-8'>
<title>Test Game</title>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
</head>
<body>
<script type="text/javascript">
var CANVAS_WIDTH = 480;
var CANVAS_HEIGHT = 320;
var canvasElement = $("<canvas>")
.attr('width', CANVAS_WIDTH)
.attr('height', CANVAS_HEIGHT);
var canvas = canvasElement.get(0).getContext("2d");
canvasElement.appendTo('body');
var FPS = 30;
setInterval(function () {
update();
draw();
}, 1000/FPS);
function update () {
}
function draw () {
canvas.fillStyle = "#000"; // Sets colour to black
canvas.fillText("Sup Bro!", 50, 50);
}
</script>
</body>
</html>
I am learning HTML5 as well. Like the previous person said, you are using jQuery ($) without including the library.
Also, from what I've learned, I think it's better to use requestAnimationFrame ( https://developer.mozilla.org/en/docs/Web/API/window.requestAnimationFrame ) instead of setInterval. If you wish to set FPS, you can put a conditional in the draw loop to check whether it is time to draw the next frame.
function draw(timestamp) {
requestAnimationFrame(draw);
if (timestamp - lasttimestamp > 1000 / framerate) {
lasttimestamp = timestamp - ((timestamp - lasttimestamp) % 1000 / framerate;
// ... put your drawing code in here
}
}
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.