Reputation: 5976
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?
Upvotes: 1
Views: 1078
Reputation: 5976
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:
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel',
include: path.join(__dirname, 'src')
},
{ test: /\.(png|jpg)$/, loader: 'url-loader?limit=90000' }
]
},
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
this.background.src = "../images/bg.jpg";
to this:
this.background.src = require('../images/bg.jpg');
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:
var image = this.background;
var _canvas = document.getElementById('canvas');
this.ctx = _canvas.getContext('2d');
var drawBackground = function (callback) {
callback(this);
}
image.onload = drawBackground(() => {
let pattern = this.ctx.createPattern(image, 'repeat');
this.ctx.fillStyle = pattern;
this.ctx.fillRect(0, 0, _canvas.width, _canvas.height);
});
image.src = require('../images/bg.jpg');
Upvotes: 2