Skip to content Skip to sidebar Skip to footer

Cannot Load Image Using Webpack Dev Server In Nodejs

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

Solution 1:

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'); 

Post a Comment for "Cannot Load Image Using Webpack Dev Server In Nodejs"