1

I was wondering if it is possible to store an image as an attribute of a js object. For example, I currently have:

twitter = {h:35, w:35, x:0, y:0, src: "./twitter.png"};
tw = new Image;
tw.src = twitter.src;

and then later in the program

context.drawImage(tw, twitter.x, twitter.y, twitter.w, twitter.h);

but I was wondering if the image src can be combined into the twitter object, so that it can be called like so

context.drawImage(twitter.src, twitter.x, twitter.y, twitter.w, twitter.h);

Thanks,

Tom

2
  • How about creating a function that creates/assembles an <img /> tag with src as twitter.src and just put in the other attributes in style="" ? Commented Dec 5, 2012 at 21:27
  • context.drawImage(new Image().src=twitter.src, twitter.x, twitter.y, twitter.w, twitter.h); is worth a shot Commented Dec 5, 2012 at 21:28

2 Answers 2

2

Yes, new Image returns an object, and you can have any object as a property value. So try this:

twitter = {h:35, w:35, x:0, y:0, src: "./twitter.png"};
tw = new Image;
tw.src = twitter.src;
twitter.src = tw;
context.drawImage(twitter.src, twitter.x, twitter.y, twitter.w, twitter.h);
Sign up to request clarification or add additional context in comments.

3 Comments

But is it possible to eliminate lines 2-4 altogether? And instantiate the image inside the twitter declaration?
You can instantiate the image as follows twitter = {h:35, w:35, x:0, y:0, src:"./twitter.png", image: new Image} but you will still need to set the image source at some point using twitter.image.src = twitter.src
that's perfect thanks! i have now trimmed it to tw = {w:35, h:35, x:0, y:0, src: "./twitter.png", img: new Image}; tw.img.src = tw.src;
0

You can use canvas's toDataURL() method to get the raw base64 bytes of the image and store that in the object

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.