[英]How to Add png Images to JS using Webpack?
I'm working on creating an HTML5 game. 我正在努力创建一个HTML5游戏。 I'm using a boilerplate that uses Webpack.
我正在使用一个使用Webpack的样板。 I've been trying to add png images from my local folder into a js file but I keep getting the following errors:
我一直在尝试将本地文件夹中的png图像添加到js文件中,但我一直收到以下错误:
GET http://localhost:3000/alien.png 404 (Not Found)
and Uncaught DOMException: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The HTMLImageElement provided is in the 'broken' state.
GET http://localhost:3000/alien.png 404 (Not Found)
和Uncaught DOMException: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The HTMLImageElement provided is in the 'broken' state.
The code I used in my canvas.js
file is as follows: 我在
canvas.js
文件中使用的代码如下:
let alienImg = new Image();
alienImg.src = 'alien.png';
c.drawImage(alienImg, 300, 300)
Am I doing something wrong in the way I'm trying to get the image on to the canvas, or is it something in my webpack.config.js file? 我在尝试将图像放到画布上的方式上做错了什么,或者是我的webpack.config.js文件中的内容?
The webpack file is below, for reference: webpack文件如下,供参考:
module: {
rules: [
{
test: /\.(js)$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['env']
}
}
},
{
test: /\.html$/,
loader: 'html-loader?attrs[]=video:src'
},
{
test: /\.mp4$/,
loader: 'url-loader?limit=10000&mimetype=video/mp4'
},
{
test: /\.png$/,
loader: "url-loader?mimetype=image/png"
}
]
},
Can anyone please help me? 谁能帮帮我吗? Thank you in advance!
先感谢您!
I just did this using: html2Canvas 我只是使用:html2Canvas
import html2canvas from 'html2canvas';
... ...
html2canvas(document.querySelector(selector)).then(canvas => {
console.log(canvas);
document.body.appendChild(canvas)
canvas.setAttribute('downloads', 'nameOfImage.png')
var image = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
window.location.href = image
});
I hope this can help in some way. 我希望这可以在某种程度上提供帮助。 If so, happy days.
如果是这样,快乐的日子。 :)
:)
When you use: 当你使用:
alienImg.src = 'alien.png';
You are giving the image a url to the image - which presumably doesn't exist at that path, (given that it's giving you a 404). 你正在给图像一个网址 - 这可能是在那条路上不存在的,(假设它给你一个404)。
I think what you want to do instead is 我想你想要做的是
import alienImage from './alien.png';
And then you can use 然后你可以使用
alienImg.src = alienImage;
What this is doing is that is giving you the correct URL of the image location - after webpack has done its bundling and exposing public resources. 这样做是为了给你正确的图像位置URL - 在webpack完成捆绑并公开公共资源之后。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.