How to get loaded image property in phaser.js? - javascript

I have a problem for getting properties of loaded image in Phaser.js.
Now I resolve it by accessing private variable (a suck method I known...):
var image = game.textures.get("imageA")
console.log("width",image.frames.__BASE.width);
Does anyone has a better solution to get these properties?
Thanks a lot.

Depending on your UseCase, you could use the getSourceImage or get method, of the Texture object.
It is abit longer, also but works (if you need/want the html element ):
var image = game.textures.get("imageA");
console.info(image.getSourceImage().width);
here the link to the documentation
Or you could use the get function of the texture (if you need/want the phaser frame):
var image = game.textures.get("imageA");
console.info(image.get().width);
here the link to the documentation
The parameter for get and getSourceImage are optional, but you could enter a name/index of a frame, if you need a specific frame.

Related

How to replace a graphic with given file in InDesign via script?

I need to replace some images in an InDesign document with a given file. This happens using the InDesign server, but scripting is almost the same as with regular InDesign, except no user interaction is possible.
What I have is a InDesign Document, the ID of an Rectangle containing some image and the Path to a new image that should replace the image.
The image should be replaced, but the settings like FitOptions etc. should stay the same. Also, the new file shall be embedded in the InDesign Document. There is already some code that sort of works:
function changeImages(doc) {
var arrayLength = changeImage.length;
for (var i = 0; i < arrayLength; i++) {
var fr = doc.textFrames.itemByID(1 * changeImage[i].id);
if (!fr)
continue;
var file = File(imagePath + changeImage[i].file);
fr.place(file);
fr.fit (FitOptions.CONTENT_TO_FRAME);
fr.fit (FitOptions.PROPORTIONALLY);
fr.fit (FitOptions.CENTER_CONTENT);
}
}
This doesn't seem right. Why is it using doc.textFrames when the object is a rectangle? I am actually confused this even works.
Also it just sets some FitOptions, but I want to keep the existing.
I am very new to InDesign scripting, so I am lost here. I am reading the docs and other resources, but I am confused. e.g why is there doc.textFrames.itemByID but nothing like that for other Frames? Do I have to iterate doc.allPageItems and compare ids?
itemByID is a method available for all pageItems and both textFrames and rectangles are subclass of pageItem. So you have access to this method from both, and it'll give the same result. You should be able to use doc.rectangles.itemByID as well. See: http://www.indesignjs.de/extendscriptAPI/indesign11/#Rectangles.html#d1e201999__d1e202138
But you are right that the description is a bit confusing, it says:
Returns the TextFrame with the specified ID.
which is obviously not the case. If you already have the IDs you want to target, you could use doc.pageItems.itemByID, which is maybe less confusing, since basically you're looking for pageItems when using itemByID.
As for fitting options, they are a property of your rectangle object, so placing a new image shouldn't change the fitting options. If you want to keep the same, simply remove the calls to fit(). See in property list of Rectangle, frameFittingOptions: http://www.indesignjs.de/extendscriptAPI/indesign11/#Rectangle.html
Josef,
I've had the same problem with InDesign CS4 with keeping the original FitOptions. I was never able to figure out how to get the settings currently being used in InDesign CS4.
To get around the problem what I did was to set the value in the Fitting on Empty Frame in the Frame Fitting Options in the InDesign document.
Then in code I used that setting, something like this:
changeImages (app.activeDocument);
function changeImages(doc)
{
with(doc)
{
var rec = doc.rectangles.itemByID(207);
var file = new File("c:\\new_image.png");
rec.place(file);
rec.fit(rec.frameFittingOptions.fittingOnEmptyFrame);
}
}

Can't access object in jquery (prevObject?)

A function in my WP plugin has just randomly (as far as I can tell) stopped working.
Here's the code in question:
window.send_to_editor = function(html) {
var classes = jQuery('img',html).attr('class');
var items = classes.split(" ");
... more stuff here
}
I've confirmed that the html variable is indeed an img html tag. Here's what firebug shows when I do a console.log of the object (console.log(jQuery('img',html));):
Object[]
context -> undefined
jquery -> "1.11.2"
length -> 0
prevObject -> Object[img.alignnone.size-full.wp-image-1234 name.jpg]
And the error it shows is classes is undefined.
I figure there's something wrong with the object I get, but this used to work recently and I'm not aware of any changes in the site that could have caused this.
I'd appreciate any input on this.
EDIT:
More info. This happens with two plugins which are supposed to be unrelated (made by different people). It happens when, after uploading an image to the server (or selecting a previously uploaded picture) you try to insert it into the post.
As I said before this error has appeared out of nowhere, it was working as intended a couple days ago. The only thing I can think of that has changed since then is the domain name, but I can't see how that could be related.
The jQuery selector always returns a jQuery object, but when the length is 0 then no elements were found matching the selector that you provided. In your example you've confirmed that nothing is selected as the length of the jQuery object is 0. Perform a check whether an element was selected like this:
var $els = jQuery('img',html),
classes;
if ($els.length) {
classes = $els.attr("class");
}
Keep in mind that your DOM query is limited by what you pass in as the html parameter. If you simply want to find the images on the page do: var $els = jQuery('img');
I finally managed to fix this; the key was parsing the html string variable into proper HTML, using jQuery.parseHTML(). Thanks to everyone who helped!

Why can't I position the browsers focus on the svg/div element that I need?

Okay, so this is annoying the hell out of me, I have a webpage with a whole bunch of svgs on it (the svg JQuery plugin), I needed the browser to focus on certain ones(horizontally), so I made a simple function to achieve my end:
function adjustWindowPos(svg){
var left = svg.scrollLeft();
$(document).scrollLeft(left);
}
Where the svg object is just an object we get via (we draw and shit to is before we do this, so it is rendered):
$("#someDivID").svg('get');
I've tested this last night and everything worked fine, this morning I come into work and it throws an error in firebug saying:
TypeError: svg.scrollLeft is not a function
I realize that it can't find the function because the object is an SVG wrapper not a JQuery object per say...but it worked yesterday. That's what I don't get (a lot of things, no coffee today).
You need to create jQuery-object that will contain svg DOM-element, that is jQuery wrapper which you are looking for. You can do it several ways using the $ jQuery function:
pass a jQuery selector string to it: $('jquery selector');
pass a DOM object to it;
get it from already existing jQuery object, if you have one;
Let me suppose that you have an id-selector:
var svg = '#id_of_the_svg_element'
function adjustWindowPos(svg){
var $svg = $(svg); // now this is the jQuery object
var left = $svg.offset().left; // this is its horizontal position relative to the document
$(document).scrollLeft(left);
}

Building a Raphael path object in piecemeal fashion

I'm trying to create a little free-hand drawing app, and to figure out a way to add path segments (e.g. "L10,10") to a Raphael path Element. This answer suggests that isn't possible.
I've tried doing something like:
var e = paper.path("M0,0L100,100")
e.attr("path").push(["L",50,100])
...which does alter the array returned by e.attr("path") but doesn't change the graphic, so I guess this isn't supported behavior.
It looks like you have to call the setter version of .attr() to update the display. The following seems to work:
var e = paper.path("M0,0L100,100");
e.attr("path").push(["L",50,100]);
e.attr("path", e.attr("path"));
although this does look pretty clumsy. I don't really see a better way to do it using push(), though.
After looking through the Raphael 2 source I figured out a method to create an incremental path efficiently, by:
initializing the path using the Raphael API w/ elem = paper.path()
attaching the mousemove handler to alter the SVG DOM path directly, via elem.node.setAttribute("d", elem.node.getAttribute("d")+newLineSegment); Raphael uses the 'd' attribute to set path string internally so this should be cross-browser compatible AFAICT (Update: actually I'm mistaken; this only works for the SVG-compatible browsers, not VML), while bypassing a whole mess of code we don't need to have run on an inner loop
when done drawing, set the path attribute for the path element explicitly through Raphael's API, so it can do all the proper housekeeping on the Element e.g.: elem.attr( {path: elem.node.getAttribute("d") })
This performs reasonably well on Chrome, and other modern browsers I tested on.
I've finished a jQuery UI widget for a sketchpad that uses this. Please leave a comment if you would find such a thing useful as open source. If there's interest I'll see if I can make that happen.
I can conform that this works:
var arr = somePath.attrs.path;
arr.push(["L", x, y]);
somePath.attr({path: arr});

Store images in Javascript object

I am not sure if this is possible, but I want to store an image in a JavaScript variable or an object and when the page loads, I want to make those images appear where desired.
I want to know if some images are converted to binary form. Can they be converted back to images with JavaScript?
It appears that the OP is requesting how to do data islands in JavaScript, specifically for images. None of the answers previously given provide such a method, so here you go.
Basically, you encode the image as a base64 string and then set that as the source of a DOM element. Setting the source of an Image object to a url is not equivalent, since it requires an addition HTTP connection.
var data = 'data:image/gif;base64,'+
'R0lGODlhAAEwAMQAAJ2M5Me98GRK1DoYyYBr3PHv++Pe99XO81Y50auc6PBkZEgpzbmt7HJa2I57'+
// snip //
'fS3CqU7XGYgE+GqHvrLJ8Tr6qXmqiwAF9CffgnMNqmWHAWNBwwGsKpKsrmJqltOOV69nuYxSkqpo'+
'Tata18rWtrr1rTIIAQA7';
var icon_elem = document.getElementById("icon_here");
icon_elem.src = data;
The above code and a full example can be found here: http://www.kawa.net/works/js/data-scheme/base64-e.html
You can simply use
var img = new Image();
img.src = "http://yourimage.jpg";
to create a DOM image.
A DOM image is an object in memory that contains the image binary form, so there's no need to convert it back to an image since it's already one.
See, this is a simple matter. But the method to approach this problem is not the way you are trying right now.
What you think will work:
We'll store the image (its binary data) in a js variable, and then slap it on the page any time.
How it will work much more easily:
you just have to create a DOM image on the page, and set its source. The browser will fetch the image from the server automatically.
Examples:
ex-1:
var img_src = "http://someserver/yourimage.png";
var node = document.getElementById('the-node-in-which-i-want-my-image');
node.innerHTML = "<img src='"+img_src+"' alt='my image'>";
ex-2: (using jquery) - this is essentially the same as above, only much easier to write:
var img_src = "http://someserver/yourimage.png";
$('#the-node-in-which-i-want-my-image')
.html("<img src='"+img_src+"' alt='my image'>");
Now, there's one more thing: the browser starts fetching the image after this code runs, so the image actually appears a little after you insert it into the DOM.
To prevent this, you can pre-fetch the images using:
var prefetch = new Image();
prefetch.src = "http://someserver/yourimage.png";
Cheers!

Categories