javascriptcanvasbackground-imagehtml5-canvasboids

Update background image through Javascript and HTML5 Canvas


Javascript is very far from being one of my strengths; therefore apologies if my question appears very remedial to many of you.

I am attempting to implement Boids through Javascript and the HTML5 Canvas. Although the flocking behaviour has been established, the application looks rather plain upon a blank background.

For this reason, I am attempting to use an image as my background, but am having difficulties.

this.draw = function() {
        /* First clear everything */
        this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);

        /* And ink them */
        this.context.strokeStyle = "#000";
        this.context.stroke();

        /* Draw each boid */
        for(var i in this.boids) {
            this.boids[i].draw(this.context, this.size);
        }
    }

If anyone has knowledge of how to paint a background image within the above function, please can you let me know :)


Solution

  • Instead of doing it in Canvas, you can more easily set a background-image in the CSS:

    http://jsfiddle.net/qwzBh/

    That way you won't have to worry about drawing it all the time.