Hi I am using the following code to try to draw a background for my game, but I keep getting the failure message and I couldn't figure out why this would happen.
This is my main.js
:
this.background = new Image();
var context = document.getElementById('canvas').getContext('2d');
var loaded = false;
var drawBackground = function () {
loaded = true;
var pattern = context.createPattern(this.background, 'repeat');
context.fillStyle = pattern;
context.fillRect(0, 0, 10000, 10000);
}
this.background.onload = drawBackground;
this.background.src = "../images/bg.jpg";
setTimeout(function() {
if (loaded) {
console.log('success');
} else {
console.log('falilure');
}
}, 3000);
My file directory structure looks like this:
- dist
- static
- bg.jpg
- bundle.js
- images
- bg.jpg
- src
- main.js
- server.js
I have tried changing this.background.src
to ./static/bg.jpg
but it still doesn't work.
I am running my code on a webpack-dev-server using the command npm run dev
. In production the source code and static files will be copied and bundled to dist
directory. But I am using the development mode so I guess the image is not copied yet. Why is my image not loaded?
I have found the solution for this after tweaking for a day. I have made several mistakes in my code.
To load the image in webpack-dev-server we need to use loaders configured in webpack.config.js (or whatever name you give to the config file of webpack-dev-server).
So I put the loader definition inside the module section like this:
Now here comes the tricky part, using the loader alone doesn't get your image displayed. You have to require it as a resource in javascript code. So in the question code I need to change
to this:
But that still doesn't work, because I was using async calls on synchronous model. I need to change the onload call to receive a callback and draw images in the callback. Then the code finally works. And it would look like this: