programicks Posted May 6, 2016 Share Posted May 6, 2016 Hi. I was testing to see if I could use the following code to store new Image() in a variable and use it for several images. var _new_image = new Image(); var _image_1 = _new_image; _image_1.src = "./assets/views/image_1.jpg"; var _image_2 = _new_image; _image_2.src = "./assets/views/image_2.jpg"; var _image_3 = _new_image; _image_3.src = "./assets/views/image_3.jpg"; So each new image created uses the _new_image variable instead of new Image() . But, of course, this isn't working. Only one image will load. So I was wondering if I can store new Image() in a variable and what the syntax/code would be to do this. Thanks. Quote Link to comment Share on other sites More sharing options...
Fatalist Posted May 6, 2016 Share Posted May 6, 2016 After var _image_1 = _new_image; ,_image_1 and _new_image will refer to the same object. When you assign an object, the object is not cloned in JS. In the end you will have only one object of Image type and its src will be "./assets/views/image_3.jpg" ; The browser will not load the image before that function ends. You can change src after the first image loads: var _new_image = new Image(); _new_image.src = "./assets/views/image_1.jpg"; _new_image.onload = function (e) { _new_image.src = "./assets/views/image_2.jpg"; _new_image.onload = function (e) { _new_image.src = "./assets/views/image_3.jpg"; _new_image.onload = ....; }; }; I don't think you need this though, you should probably just create an array of Image-s. Quote Link to comment Share on other sites More sharing options...
programicks Posted May 6, 2016 Author Share Posted May 6, 2016 Hi. Thanks for the answer, yes, I was just thinking about using an array for the rest of my images rather than just the hero and inventory images that I do now but I will take a look at your code. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.