微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

静态图像在开发过程中未使用 Webpack 加载并崩溃 html5 画布元素

如何解决静态图像在开发过程中未使用 Webpack 加载并崩溃 html5 画布元素

对以下内容的任何帮助将不胜感激。我只是想用 vanilla JS 设置 webpack。

我在使用 Webpack 时似乎无法加载任何图像,最终在尝试绘制它时在我的 html5 canvas 元素中抛出错误。我尝试使用多张图片

我试过在下面使用这个:

const bang = new Image();
bang.src = 'img/boom.png';
...
...
ctx.drawImage(bang,element.x,element.y);

一个控制台错误是 404 - 找不到图像。

导航到图像路径会在我的浏览器中显示

Cannot GET /img/boom.png

我可以在页面源中看到“加载”了一个图像,但显然加载不正确:

Image not loading

即使尝试导航到那个,我也一样:

Cannot GET /255b91fcdc063fc03c4f.png

我也试过只使用

<img src="..." />

在 .html 文件中,但这也不会渲染图像。

webpack.config.js:

const webpack = require("webpack");
const path = require("path");
const HtmlWebPackPlugin = require("html-webpack-plugin");
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");


module.exports = (env,argv) => {
  let isProd = false;

  if(argv.mode !== 'production'){
    console.log('Outputting code in dev mode - non minified.');
  } else if (argv.mode === 'production'){
    isProd = true;
    console.log('Building production ready code - minified & ready to deploy.');
  }

  return{
    entry: "/js/main.js",output: {
      filename: "[name].min.js",path: path.resolve(__dirname,"dist")
    },resolve: {
      // All resolvable extensions.
       extensions: [".js",".jsx",".css",".scss"],alias: {
        images: path.resolve(__dirname,'/img')
      }
    },// Enable sourcemaps for debugging webpack's output.
    devtool: "source-map",devServer: {
      contentBase: "/dist",hot: true
    },optimization: {
      minimize: isProd,minimizer: isProd ? [
        new OptimizeCSSAssetsPlugin({})
      ] : []
    },module: {
      rules: [        
        {
          test: /\.js?$/,exclude: /node_modules/,use: {
            loader: "babel-loader"
          }
        },{
          test: /\.html$/,use: [
            {
              loader: "html-loader"
            }
          ]
        },{
          test: /\.scss$/,use:  [  
            "style-loader",MiniCssExtractPlugin.loader,"css-loader?sourceMap","sass-loader?sourceMap"
          ]
        },{
          test: /\.(png|svg|jp(e*)g|gif|eot|ttf|woff|woff2)$/,use: [
            'url-loader',{ 
              loader: "image-webpack-loader",options: {
                disable: true,// webpack@2.x and newer
                limit: 8000,name: 'img/[hash]-[name].[ext]',publicPath: 'assets'
              }
            }
          ]
        }
      ]
    },plugins: [
      // Cleans dist folder when building project.
      new CleanWebpackPlugin(),// Html Webpack Plugin
      new HtmlWebPackPlugin({
        favicon: "favicon.ico",template: path.join(__dirname,"index.html"),filename: "index.html",title: "game"
      }),new MiniCssExtractPlugin({
        // Options similar to the same options in webpackOptions.output
        // both options are optional
        filename: isProd ? "[name].css" : "[name].[hash].css",chunkFilename: isProd ? "[id].css" : "[id].[hash].css",ignoreOrder: false
      })
    ]
  };
};

编辑:.babelrc 文件添加

{
    "presets": [
        [
            "@babel/preset-env",{
                "targets": "> 0.25%,not dead","useBuiltIns": "usage","corejs": 3
            }
        ]
    ],"plugins": ["@babel/plugin-transform-runtime"]
}

我尝试过使用 file-loader 而不是 url-loader,但似乎没什么区别。

文件结构(main.js在/js下,boom.png在/img下):

enter image description here

奇怪的是,favicon.ico 渲染得很好(在 webpack.config.js 中引用)。

最终,这会导致 Canvas 元素在尝试渲染图像时抛出以下错误

Uncaught DOMException: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The HTMLImageElement provided is in the 'broken' state.

解决方法

使用 import 在脚本中加载图像。

import BoomImg from 'img/boom.png';

const bang = new Image();
bang.src = BoomImg;
...
...
ctx.drawImage(bang,element.x,element.y);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?