Katelyn
Katelyn

Reputation: 13

Change Background of Canvas using JavaScript

I am working on a project and had the idea to create a button that would generate a number using Math.floor and Math.random to select an image in an array, and then apply it as a background to my canvas.

I have been fiddling around with changing just the background color before getting images in the code, and I was curious if there is a way to change the background using a JavaScript function. So far the only way I have been able to change the canvas background is by editing the background-color in css, then putting the styles in the head and foregoing the css altogether.

Is this possible?

Upvotes: 0

Views: 4580

Answers (1)

Martijn de Langh
Martijn de Langh

Reputation: 425

An HTML canvas can be drawn upon, the first image that is drawn on the canvas will be behind the second image. In order to make a canvas have a "background" you should use the draw function to draw the image on x 0 and y 0 with the width and height of the canvas.

See how to use the draw function here: http://www.w3schools.com/tags/canvas_drawimage.asp

Upvotes: 1

Related Questions