J. Unkrass
J. Unkrass

Reputation: 772

How to load images and spritesheets with Phaser 3 and Webpack correctly?

I have a Vue app with Webpack and Phaser 3 and I am trying to load images and spritesheets in my main scene.

import Phaser from 'phaser'

export class MainScene extends Phaser.Scene {
  constructor () {
    super({
      key: 'MainScene'
    })
  };

  preload () {
    this.load.image('sand', require('@/assets/sand.png'))
    this.load.spritesheet('dude', require('@/assets/dude.png'), { frameWidth: 32, frameHeight: 48 })
  };

  create () {
   this.add.tileSprite(0, 0, 800, 600, 'sand').setOrigin(0, 0)

   let player = this.physics.add.sprite(100, 450, 'dude')
   player.setCollideWorldBounds(true)
  }

  update () {
   // update
  }
}

This works fine for the sand image, but not for the spritesheet dude.png, which I downloaded from the Phaser tutorial here. My browser console output is

Local data URIs are not supported: dude

After researching, I found this tutorial to use data URIs in Phaser. After using that technique the spritesheet is loaded, but what I found out is that Webpack requires both images differently and I cannot figure out why. Also it is not recommended to use lots of data URIs when deploying the app to a server.

require('@/assets/sand.png') resolves to "/static/img/sand.79c51a8.png"

require('@/assets/dude.png') resolves to a base64 string.

My Webpack conf seems to have the correct loader

{
  test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
  loader: 'url-loader',
  options: {
   limit: 10000,
   name: utils.assetsPath('img/[name].[hash:7].[ext]')
}

Does anyone know why this happens?

[EDIT]: Keeri's comment helped me find out that the sand image is bigger than the dude image, and even way bigger than the limit set for the url-loader in the Webpack config. So I set the limit to 1 to always fall back to the file-loader, which seems to work fine for every image.

It feels a bit hacked to define the url-loader and then skip it, but from what I've read, Phaser doesn't want images base64 anyway. So maybe the best way is to remove the url-loader from my Webpack config.

Upvotes: 5

Views: 3171

Answers (1)

keeri
keeri

Reputation: 814

limit: 10000 sets the maximum size of a file in bytes, if your image exceeds that size, then the default file-loader (file path) is used rather than url-loader (base64)

Upvotes: 2

Related Questions