RainingChain RainingChain - 5 months ago 32
Javascript Question

Create a New Image() in 1 Line

Right now, I'm using

var lifeIcon = new Image();
lifeIcon.src = "img/System/lifeIcon.png";

Is there a way to do the same thing in 1 line?

I tried

var lifeIcon = (new Image()).src = "img/System/lifeIcon.png";

But it doesn't work. lifeIcon is considered as a string...


Note: I have many, many images. My goal is to use the Image in a canvas.


function newImage(src){
var tmp = new Image();
tmp.src = src;
return tmp

var lifeIcon = newImage("img/System/lifeIcon.png");
var closeIcon = newImage("img/System/closeIcon.png");
var goldIcon = newImage("img/System/goldIcon.png");

Note: I personally find it faster to write and faster to read that way, especially because I have many images.


It sort of depends on what you're doing next. If the only other thing you need is to append it, then you can do this:

element.appendChild(new Image()).src = "img/System/lifeIcon.png";

This works because .appendChild() returns the newly appended element.

If you need to assign other properties, then you may simply want to create a helper function that lets you pass an object holding the properties and values.

function create(name, props) {
    var elem = document.createElement(name);
    for (var p in props)
        elem[p] = props[p];
    return elem;

This is a very simple function, and could be expanded a bit, but you get the idea.

var el = create("img", {src: "img/System/lifeIcon.png"});