Unit 3: Create a background with an image?

Is there a way to create a background with an image the student has? If so, what does the code look like? I am looking for this to happen in Unit 3, Game Lab.

I haven’t worked with Unit 3 yet but one of my students used a picture of chocolate ice cream as his background. Here is the style.css coding
body {
background-image: url(“chocolate.jpeg”);

}

@bobd is correct for Unit 2! That CSS will work. Here are some resources that will control whether it repeats etc. https://www.w3schools.com/cssref/css3_pr_background.asp. You can also control if it scrolls or is fixed https://www.w3schools.com/cssref/pr_background-attachment.asp.

If your question was about Game Lab, let us know.
Michelle

I would like to know this for Unit 3, Game Lab

Ahh…you upload the photo as a sprite and add it to your code so that it is all the way in the back. Here is an example of a simple scene where the background is a sprite (vs just the background color block). https://studio.code.org/projects/gamelab/cOj6ZcO4LeKLvCUlDwlq4ymU85ATl1NZJV09ILPAYtk

Good luck!
Michelle

1 Like

Yes. You can add a picture as a background by creating a background sprite. Keep in mind that the sequencing of commands matters in javascript. So if you have a showScore() function to display a scoreboard for the game, it would have to be called after the drawSprites() call. Here is an example:

var gameBackground = createSprite(200, 200);
gameBackground.setAnimation("day");
gameBackground.scale = 3;

var dayBtn = createSprite(200, 350, 40,30);
dayBtn.setAnimation("dayBtn");

var nightBtn = createSprite(300, 350, 40, 30);
nightBtn.setAnimation("nightBtn");

var score = 0;

function draw() {
  chooseBackground();
  drawSprites();
  showScore();
}

function showScore(){
  textSize(20);
  fill("orange");
  text("Score:", 10, 25);
  text(score, 70, 25);
}

function chooseBackground(){
  if(mousePressedOver(dayBtn))
    gameBackground.setAnimation("day");
  else if(mousePressedOver(nightBtn))
    gameBackground.setAnimation("night");
}

Link to the sample