I tried following the tutorial suggested in answer to the question at Drag and Drop canvas in HTML5 but when I load my page in Firefox, the Firebug console displays an error saying that “canvas is null”.
The file it’s complaining about is the JS file where I’ve put the code for user interaction:
var canvas;
var ctx;
var x = 75;
var y = 50;
var WIDTH = 400;
var HEIGHT = 300;
var dragok = false;
function rect(x,y,w,h) {
ctx.beginPath();
ctx.rect(x,y,w,h);
ctx.closePath();
ctx.fill();
}
function clear() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
}
function init() {
canvas = document.getElementById("gameCanvas");
ctx = canvas.getContext("2d");
return setInterval(draw, 10);
}
function draw() {
clear();
ctx.fillStyle = "#FAF7F8";
rect(0,0,WIDTH,HEIGHT);
ctx.fillStyle = "#444444";
rect(x - 15, y - 15, 30, 30);
}
function myMove(e){
if (dragok){
x = e.pageX - canvas.offsetLeft;
y = e.pageY - canvas.offsetTop;
}
}
function myDown(e){
if (e.pageX < x + 15 + canvas.offsetLeft && e.pageX > x - 15 +
canvas.offsetLeft && e.pageY < y + 15 + canvas.offsetTop &&
e.pageY > y -15 + canvas.offsetTop){
x = e.pageX - canvas.offsetLeft;
y = e.pageY - canvas.offsetTop;
dragok = true;
canvas.onmousemove = myMove;
}
}
function myUp(){
dragok = false;
canvas.onmousemove = null;
}
init();
canvas.onmousedown = myDown;
canvas.onmouseup = myUp;
The main error is “canvas is null”, and when I expand that, it complains about init() on line 22, interaction.js() on line 57.
Line 22 is the line:
ctx = canvas.getContext("2d");
and line 57 is the line:
init();
Could someone point out to me where I’m going wrong?
Cheers.
The HTML where my canvas is is this:
<canvas id="gameCanvas" width="1000" height="500" style="border:1px solid">
Your browser does not support the canvas element.
</canvas>
It seems when your
init()method is called thecanvasis not rendered.Use