0

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?

7
  • possible duplicate of change background using javascript otherwise you can google it Commented Aug 12, 2015 at 13:15
  • What you're looking for is editing the style property of the element - this has the same effect as modifying the CSS file. eg: myElement.style = "background-color: blue; font-size: 30px;" Commented Aug 12, 2015 at 13:17
  • I know how to change the background by the style element by typing a color, I just am unsure if I can use a JavaScript function in the style property and if I can, how to do so. Commented Aug 12, 2015 at 13:23
  • You can easily use var myBackgroundColor = '#dd0300'; myElement.style.backgroundColor = myBackgroundColor;. Wrapping this in a function could be function changeBG(element, hexcode){ element.style.backgroundColor = hexcode;} and then use it like changeBG (document.querySelector('canvas'),'#dd0300') Commented Aug 12, 2015 at 13:35
  • 1
    You could always use a fillRect in your canvas code which will then fill in the canvas, or use CSS and use the code @somethinghere has provided Commented Aug 12, 2015 at 14:02

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

That is true, although a canvas is transparent by default so it might be easier to use background-color. But yeah, I would have suggested this too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.