我正在使用 HTML5 画布和 JavaScript 来制作一个基本游戏,我有一个数字 1-10 的图像数组,然后还有另一个数字 1-10 的威尔士单词数组。
我想要做的是从图像数组中选择一个随机元素,从单词数组中选择一个随机元素,并将它们都显示在画布上。然后,用户将单击一个勾号以指示该单词是否代表正确的数字,如果不是,则单击叉号。
问题是我不确定如何将数组元素绘制到画布上。我有以下代码,在我考虑如何随机选择绘制的元素之前,我将使用它来测试它是否有效:
function drawLevelOneElements(){
/*First, clear the canvas */
context.clearRect(0, 0, myGameCanvas.width, myGameCanvas.height);
/*This line clears all of the elements that were previously drawn on the canvas. */
/*Then redraw the game elements */
drawGameElements();
/*Now draw the elements needed for level 1 (08/05/2012) */
/*First, load the images 1-10 into an array */
var imageArray = new Array();
imageArray[0] = "1.png";
imageArray[1] = "2.png";
imageArray[2] = "3.png";
imageArray[3] = "4.png";
imageArray[4] = "5.png";
imageArray[5] = "6.png";
imageArray[6] = "7.png";
imageArray[7] = "8.png";
imageArray[8] = "9.png";
imageArray[9] = "10.png";
/*Then create an array of words for numbers 1-10 */
var wordsArray = new Array();
wordsArray[0] = "Un";
wordsArray[1] = "Dau";
wordsArray[2] = "Tri";
wordsArray[3] = "Pedwar";
wordsArray[4] = "Pump";
wordsArray[5] = "Chwech";
wordsArray[6] = "Saith";
wordsArray[7] = "Wyth";
wordsArray[8] = "Naw";
wordsArray[9] = "Deg";
/*Draw an image and a word to the canvas just to test that they're being drawn */
context.drawImage(imageArray[0], 100, 30);
context.strokeText(wordsArray[3], 500, 60);
}
但由于某种原因,当我在浏览器中查看页面时,在 firebug 控制台中,我收到错误:
无法转换 JavaScript 参数 arg 0 [nsIDOMCanvasRenderingContext2D.drawImage] context.drawImage(imageArray[0], 100, 30);
我不确定这是否是我要访问数组元素 0 中的图像的方式......有人可以指出我做错了什么吗?
* 编辑 *
我已将 to 数组下方的代码更改为:
var image1 = new Image();
image1.src = imageArray[0];
/*Draw an image and a word to the canvas just to test that they're being drawn */
context.drawImage(image1, 100, 30);
context.strokeText(wordsArray[3], 500, 60);
但由于某种原因,wordsArray 中的唯一元素被绘制到画布上——imageArray 中的图像元素根本不显示。
有任何想法吗?