Jerome Papalie
Jerome Papalie

Reputation: 49

How to Add png Images to JS using Webpack?

I'm working on creating an HTML5 game. I'm using a boilerplate that uses Webpack. I've been trying to add png images from my local folder into a js file but I keep getting the following errors:

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.

The code I used in my canvas.js file is as follows:

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?

The webpack file is below, for reference:

 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!

Upvotes: 3

Views: 1391

Answers (2)

waz
waz

Reputation: 1253

I just did this using: 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. :)

Upvotes: 1

dwjohnston
dwjohnston

Reputation: 11813

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).

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.

Upvotes: 0

Related Questions