2

我尝试按照在 HTML5 中拖放画布中回答问题时建议的教程进行操作,但是当我在 Firefox 中加载我的页面时,Firebug 控制台会显示一条错误消息,指出“画布为空”。

它抱怨的文件是我放置用户交互代码的 JS 文件:

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;

init()主要错误是“canvas is null”,当我展开它时,它在第 22行第 57 行抱怨。第 22interaction.js()行是以下行:

 ctx = canvas.getContext("2d");

第 57 行是以下行:

init();

有人可以指出我哪里出错了吗?

干杯。

我的画布所在的 HTML 是这样的:

<canvas id="gameCanvas" width="1000" height="500" style="border:1px solid">
    Your browser does not support the canvas element.
    </canvas>
4

2 回答 2

1

似乎在init()调用您的方法时canvas未呈现。
采用

window.onload = function() {
  init();
};
于 2012-11-27T12:56:22.633 回答
0

我在这里测试了您的代码:http: //jsfiddle.net/agryson/wfxeH/ 我很确定您可能在画布的 id 中出错了。确保您的 HTML 具有:

<canvas id="gameCanvas"></canvas>
于 2012-11-27T12:57:08.893 回答