html5 canvas array of images- draw image to canvas

Related searches

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.

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.

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 */
            /*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);

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?

* EDIT *

I've changed the code below the to arrays 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.

Any ideas?

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

        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!

Pixel manipulation with canvas, Until now we haven't looked at the actual pixels of our canvas. With the ImageData object you can directly read and write a data array to manipulate pixel data. We will can be controlled and how to save images from your canvas. drawImage(img, 0, 0); = 'none'; var imageData = ctx. The drawImage () method draws an image, canvas, or video onto the canvas. The drawImage () method can also draw parts of an image, and/or increase/reduce the image size. Note: You cannot call the drawImage () method before the image has loaded.

This is the code for drawGameElements()

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

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

            /* 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.

Add Image to HTML5 Canvas using JavaScript, You can use JavaScript to add an image to an HTML5 Canvas element, dynamically. The <canvas> element is useful for drawing images, to create graphs,� Although HTML has long had support for images, JavaScript’s canvas interface adds new life to web images. Images can be displayed inside a canvas, where they can be integrated with the vector-drawing techniques of the canvas API. You can also select a portion of an image to display and apply the various transformations to your …

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:

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

4. Images on the Canvas - HTML5 Canvas [Book], Images on the Canvas Like the Canvas Drawing API, the Canvas Image API is arrays of pixel data that we can manipulate and then draw back to the canvas. Dynamic images are drawn on canvas, which is represented by the <canvas> element. This element MUST have the width and height attributes set. If we don't specify them or set them in CSS, some browsers will not understand and the result will be blurred. However, we can't draw directly on the <canvas> element, we must get its context first.

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

    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";
    //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) 
     context.drawImage(imgs[ri], cx, cy);
     cy += imgs[ri].height + space;
     callDraw(context, imgs, cx, cy, ri, space);

How displaying an image on HTML5 canvas works —, Dive into the details of canvas's drawImage API, also, learn how to once you understand the whole picture it's a downhill bicycle ride on a� Canvas is an element for drawing graphic on webpage with JavaScript which responsible for majority of stunning effect on today’s website. In this tutorial, we’ll show you how to load an existing image to canvas with JavaScript, which could be further used for image processing or pixel manipulation down the road.

How To Optimize Images With HTML5 Canvas — Smashing Magazine, The canvas pixel array is a plain array containing each pixels's RGBa data. getContext('2d'); // Draw image on canvas to get its pixel data ctx. Recommend:javascript - html5 canvas array of images- draw image to canvas. ages for the numbers 1-10, and then have another array for the Welsh words for the numbers 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 canva

1) Add Image to Canvas Using image() Object. In the first method, I’ll use JavaScript image() object to load an image and initialize the object with the image source. This is one of the simplest ways to dynamically add an image to your web page and I’ll use this technique to add the image to the canvas element.

Use HTML5 canvas' drawImage method in JavaScript: The drawImage method can be invoked with three different set of arguments: context.drawImage(image, dx, dy) context.drawImage(image, dx, dy, dw, dh) context.drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh) where d represents the destination canvas and s represents the source image. drawImage

  • creating a JSFiddle will help us
  • Sorry, I don't know what a JSFiddle is? How do I create one?
  • Sorry. There is a cool site called JSFiddle. You can go there and make a simple mock up of your code, and then you can share that with us, and we can troubleshoot your issue easier.
  • I've tried making a JSFiddle... but I don't know if what I've done is right... The URL to the page I made on that site is: but it doesn't seem to be displaying the page properly in the preview panel. Or at least it doesn't appear to be displayed the same way as when I view the page in a browser. The URL for my live page is:… You'll have to click Start first, when it updates, only the cross has an event listener
  • Thanks for your reply. I've done what you said, but for some reason, only the word is drawn to the canvas- the image isn't. I've updated my original post to show what I've done.
  • I think the only thing which would stop the image being drawn would be the path. Where are you images located in relation to the website root? In firefox, in firebug, you should be able to see GET requests being made to '1.png' etc. I would expect those are being shown as 404's?
  • I thought 404's were 'page not found' errors? They're not 404s, the image just isn't being displayed. The image is a .png file, and it's in the same root directory as the webpage that I'm trying to display it on. It's got something to do with the fact that I'm trying to display the image on the HTML5 canvas, but I just can't work out what the problem is.
  • 404's are effectively page not found, but they can occur from any HTTP request if the target isn't there. Assuming your images are there and the GET request returns a 200 then yeah the issue will be in the code, what is 'drawGameElements();' doing in your code?
  • Ok, somehow it seems to have started working now. Thanks for all your help
  • Actually, it only seems to work sometimes... sometimes it takes a number of clicks on the canvas before the iamge appears, other times it doesn't appear at all... it seems to be completely random as to whether the image appears on the first click (click on the button)- as it should, or whether it appears on a subsequent click on the canvas, or whether it doesn't appear at all... I'm really confused by this. Any suggestions?
  • The image isn't displayed because it hasn't yet been gathered by the server(this also happens with specialty fonts). Each time you attempt to load an image, that hasn't been loaded before, a GET request is sent. Meaning that some images take a bit of time before they can be used. An easy way to work around this is to either create a setTimeout() every time you load an image, or to cycle though and load all images at the beginning, so that they will be there when you want call them.