在pixi.js中创建通过文件加载器加载的纹理

时间:2017-08-09 18:01:13

标签: typescript webpack pixi.js webpack-file-loader

您好我使用Webpack,TypeScript和fileloader设置了一个项目。

我的webpack.config.js

const path = require('path');

module.exports = {
  entry: './src/index.ts',
  devtool: 'source-map',
  resolve: {
    extensions: ['.ts', '.tsx', '.js', '.jsx']
  },
  module: {
    rules: [
      {
        test: /\.ts$/,
        enforce: 'pre',
        loader: 'tslint-loader',
        options: { /* Loader options go here */ }
      },
      {
        test: /\.(png|svg|jpg|gif)$/,
        use: [
          'file-loader'
        ]
      },      
      {
        test: /\.tsx?$/,
        loader: 'awesome-typescript-loader'
      }
    ]
  },
  devtool: 'inline-source-map',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  }
};

我的tsconfig.json

{
    "module": "commonjs",
    "target": "es6",
    "noImplicitAny": true,
    "moduleResolution": "node",
    "compilerOptions": {
        "noImplicitAny": true,
        "removeComments": true
    },
    "sourceMap": true,
    "outDir": "dist",
    "baseUrl": ".",
    "paths": {
        "*": [
            "node_modules/*",
            "src/types/*"
        ]
    },
    "exclude": [
        "node_modules"
    ]
}

我的index.ts

import * as  _ from 'lodash';
import * as PIXI from 'pixi.js';

const renderer = PIXI.autoDetectRenderer(256, 256,
    { antialias: false, transparent: false, resolution: 1 });

document.body.appendChild(renderer.view);

const stage = new PIXI.Container();

renderer.render(stage);

上述星座按预期将舞台呈现为index.html

现在我在bs.png文件夹中添加了src/images/文件,现在我的项目结构如下:

enter image description here

据我了解,此bs.png作为文件/dist/14145c56ece7799954586ba6f8464dbb.png加载。我的麻烦开始了。我尝试按如下方式加载图像。首先,我创建了一个custom.d.ts,其中包含一个用于加载.png文件的模块声明:

declare module "*.png" {
  const content: any;
  export default content;
}

现在在index.ts我通过import * as Image from './images/bs.png';加载它。结果Image是类型函数,console.log(Image)的输出是14145c56ece7799954586ba6f8464dbb.png。不幸的是我无法加载像这样的Pixi纹理:

const text = new PIXI.Texture(Image);

有了这条线,我得到了:

src/index.ts(12,31): error TS2345: Argument of type 'typeof "*.png"' is not assignable to parameter of type 'BaseTexture'.
  Property 'touched' is missing in type 'typeof "*.png"'.

我理解。我也不能用:

const texture = PIXI.utils.TextureCache[Image];

虽然Image似乎确实返回了文件路径。我尝试使用webpack创建的png的文件路径加载图像,但纹理仍为undefined

我真的不确定这里真正的问题是什么。我是否需要运行服务器(如快递)或者我只是缺少某些东西?顺便说一下,这是使用npm run build的{​​{1}}命令的输出:

awesome-typescript-loader

1 个答案:

答案 0 :(得分:0)

您有图像路径,需要在使用前加载它。

 PIXI.loader.add([
        Image,
        "and_others_if_any.png",
       ])
        .load(() => {
           var sprite = new PIXI.Sprite(PIXI.Texture.fromImage(Image));

       });

此操作将执行ajax请求,因此您需要从服务器提供这些文件。如果您使用的是Linux,则可以通过从工作目录运行python -m SimpleHTTPServer 8000命令来提供服务。