javascript html5 画布图像数组 - 将图像绘制到画布

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10513480/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 10:07:17  来源:igfitidea点击:

html5 canvas array of images- draw image to canvas

javascripthtml5-canvasdrawimage

提问by Someone2088

I'm using the HTML5 canvas and JavaScript to make a basic game, and I have an array of images for the numbers 1-10, and then have another array for the Welsh words for the numbers 1-10.

我正在使用 HTML5 画布和 JavaScript 制作一个基本游戏,我有一个数字 1-10 的图像数组,然后还有另一个数字 1-10 的威尔士单词数组。

What I want to do is select a random element from the images array and a random element from the words array and display them both on the canvas. The user will then click on a tick to indicate if the word represents the correct number, or a cross if it doesn't.

我想要做的是从图像数组中选择一个随机元素,从 words 数组中选择一个随机元素,并将它们都显示在画布上。然后,用户将单击勾号以指示该词是否代表正确的数字,如果不正确则单击叉号。

The problem is that I'm not sure how to draw an array element to the canvas. I have the following code, which I was going to use just to test that it works, before I think about how to make the elements drawn be chosen at random:

问题是我不确定如何将数组元素绘制到画布上。我有以下代码,在我考虑如何随机选择绘制的元素之前,我将使用它来测试它是否有效:

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);
        }

but for some reason, when I view the page in the browser, in the firebug console, I get the error:

但出于某种原因,当我在浏览器中查看页面时,在萤火虫控制台中,我收到错误消息:

Could not convert JavaScript argument arg 0 [nsIDOMCanvasRenderingContext2D.drawImage] context.drawImage(imageArray[0], 100, 30);

无法转换 JavaScript 参数 arg 0 [nsIDOMCanvasRenderingContext2D.drawImage] context.drawImage(imageArray[0], 100, 30);

I'm not sure if this is how I'm meant to access the image in array element 0... could someone please point out what I'm doing wrong?

我不确定这是否是我打算访问数组元素 0 中的图像的方式……有人可以指出我做错了什么吗?

* EDIT *

* 编辑 *

I've changed the code below the to arrays to:

我已将 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);

but for some reason, the only the element from the wordsArray is drawn to the canvas- the image element from imageArray isn't displayed at all.

但出于某种原因,只有来自 wordsArray 的元素被绘制到画布上 - 来自 imageArray 的图像元素根本没有显示。

Any ideas?

有任何想法吗?

采纳答案by dougajmcdonald

You need to create a javascript image with it's src set to your array value

您需要创建一个 javascript 图像,并将其 src 设置为您的数组值

        var img = new Image();
        img.src = imageArray[0];

        ctx.drawImage(img, 100, 30);

Without doing that you're trying to ask the canvas to draw a string of "1.png" for example which is not what you're after here!

如果不这样做,您将试图要求画布绘制一串“1.png”,例如这不是您在这里所追求的!

回答by Noble-Surfer

This is the code for drawGameElements()

这是 drawGameElements() 的代码

/* This function draws the game elements */
        function drawGameElements(){

            /* Draw a line for the 'score bar'. */
            context.moveTo(0, 25);
            context.lineTo(700, 25);
            context.stroke();

            /* Draw current level/ total levels on the left, and current score on the right. */
            context.font = "11pt Calibri"; /* Text font & size */
            context.strokeStyle = "black"; /* Font colour */
            context.strokeText(currentLevel + "/" + totalLevels, 10, 15);
            context.strokeText(currentScore, 650, 15);
        }

Literally, all it's doing is drawing a 'score bar' on the canvas, which is just a line across the top, the current level/ total levels, and the user's current score. I don't think this is the issues, as the elements that this function is meant to display are being displayed correctly.

从字面上看,它所做的只是在画布上绘制一个“分数条”,它只是一条横跨顶部的线、当前级别/总级别以及用户的当前分数。我不认为这是问题所在,因为此功能要显示的元素正在正确显示。

回答by WikiPlugs

This is an old one but the reason why the image is not showing is probably because you have to call onLoad then set the src like so:

这是一个旧的,但图像未显示的原因可能是因为您必须调用 onLoad 然后像这样设置 src:

var img = new Image();
img.onLoad = function() {ctx.drawImage(img, 100, 30);};
img.src = imageArray[0];

回答by ?ngelo Magno de Jesus

I solved this using recursive calls on the method img.onload to draw images. E.g.:

我使用递归调用 img.onload 方法来绘制图像解决了这个问题。例如:

    var cx = 10;//x initial position to draw
    var cy = 10;//y initial position to draw
    var space = 300; //distance between images to draw
    var imageArray = new Array();
    imageArray[0] = "1.png";
    imageArray[1] = "2.png";
    imageArray[2] = "3.png";
    //etc....
    //build a Image Object array
    var imgs = new Array();
    for(i = 0; i < imageArray.length; i++){
     imgs[i] = new Image();
     imgs[i].src = imageArray[i];//attention if the images are in a folder 
    }
    var ri = 1;//index of images on the array
    imgs[0].onload = function(){
     context.drawImage(imgs[0], cx, cy);
     cy += imgs[0].height + space;
     callDraw(context, imgs, cx, cy, ri, space);
    }

The recursive function is defined as following:

递归函数定义如下:

    function callDraw(context, imgs, cx, cy, ri, space){
     if(ri == imgs.length) 
      return;
     context.drawImage(imgs[ri], cx, cy);
     cy += imgs[ri].height + space;
     ri++;
     callDraw(context, imgs, cx, cy, ri, space);
    }