1

I just want to ask a simple question, how do I load an image and make it as a background in my html5 canvas

var bg;

function setup() {
  createCanvas(600,400)
  bg = loadImage("https://mcdn.wallpapersafari.com/medium/1/92/T1iecJ.jpg")
}

function draw() {
  background(bg)
}

i tried that method but the screen only showing whitescreen, i've search for it but i can't get the solution.

Rabbid76
  • 202,892
  • 27
  • 131
  • 174

1 Answers1

5

loadImage doesn't load an image synchronously. The image may not be immediately available for rendering.

Use the preload() function, to ensure that the image is load before draw() is executed. setup will wait until any load calls within preload() have finished.

var bg;

function preload(){
    bg = loadImage("https://raw.githubusercontent.com/Rabbid76/graphics-snippets/master/resource/texture/background.jpg")
}

function setup() {
    createCanvas(600,400)
}

function draw() {
    background(bg)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.js"></script>
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
  • the page only shows loading, and the image isn't coming out – Deven Valisten Nov 10 '19 at 13:49
  • @DevenValisten Then the image path is wrong or you don't have access to it. – Rabbid76 Nov 10 '19 at 13:54
  • @DevenValisten The image is not allowed to be load: *"Access to image at 'https://mcdn.wallpapersafari.com/medium/1/92/T1iecJ.jpg' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.*" – Rabbid76 Nov 10 '19 at 14:04