Parsing XML Text with jQuery - javascript

I'm working with a database that has X and Y points per group, it's being used to draw outlines of images.
Right now in my web side this code is what I use to get the points:
var Drawing = $(XML).find('DrawingXML');
alert($(Drawing[1]).text());
Result:
<DrawingPoints>
<Point><X>1</X><Y>2</Y></Point>
<Point><X>2</X><Y>4</Y></Point>
<Point><X>3</X><Y>5</Y></Point>
<Point><X>2</X><Y>2</Y></Point>
<Point><X>0</X><Y>4</Y></Point>
</DrawingPoints>
Using the .replace() call only changes one item so it's usable for something like this:
.replace("</DrawingPoints>","");
but if I want to replace all 'Point' tags I'm out of luck.
My goal is to use the canvas feature to draw the points out so I want it to be parsed like this:
ctx.beginPath();
ctx.moveTo(1,2);
ctx.lineTo(2,4);
ctx.lineTo(3,5);
ctx.lineTo(2,2);
ctx.lineTo(0,4);
ctx.stroke();
I'm not going to use this with IE browsers just Safari/Chrome, if that helps out.

In this case you'll probably save an awful lot of brainache by using a library instead of writing your own code.
I reckon d3 does what you need:
d3.xml
d3.geo.path

Check out this question/answer. It's not Prototype specific and should help you here.
How to parse XML string with Prototype?

Get all your X and Y values at once:
var points = {};
points.X = Array();
points.Y = Array();
var ix = 0;
$(XML).find('DrawingXML DrawingPoints Point X').each(function()
{
points.X[ix++] = $(this).text();
});
$(XML).find('DrawingXML DrawingPoints Point Y').each(function()
{
points.Y[ix++] = $(this).text();
});
This might not be exact, I didn't test it and my Javascript is a bit rusty, but you get the idea.

Related

Search SVG in svg-pan-zoom

So I am using svg-pan-zoom to display a dynamically loaded SVG element. The code for loading the element is similar to the example here: https://ariutta.github.io/svg-pan-zoom/demo/dynamic-load.html (to see what I mean, view the source).
What I am trying to do is search the SVG document for text tags that match a specific query. I found an example here which seems like the solution to that part, but I can't find anything on how to access the SVG content inside svg-pan-zoom.
I'm afraid I don't have any code... I've been doing trial-and-error for quite a while now. Basically I'm just trying to figure out how to access the SVG content so I can search it.
Thanks!
I think this answer can be useful: Pan to specific X and Y coordinates and center image svg-pan-zoom
For example, let's suppose you want to look for a string that is contained inside a tspan (since you are not giving more details), then you can have a search box, and when it changes, the following function is called:
function searchTerm() {
let term = this.value;
var tspans = document.getElementsByTagName("tspan");
var found;
for (var i = 0; i < tspans.length; i++) {
if (tspans[i].innerHTML.includes(term)) {
found = tspans[i];
break;
}
}
let position = found.parentNode.parentNode.getAttribute("transform").split("translate(")[1].split(")")[0];
let posX = position.split(",")[0];
let posY = position.split(",")[1];
panZoom.zoom(1);
panZoom.pan({x:0,y:0});
var realZoom= panZoom.getSizes().realZoom;
panZoom.pan
({
x: -(posX*realZoom)+(panZoom.getSizes().width/2),
y: -(posY*realZoom)+(panZoom.getSizes().height/2)
});
}
As you can see, this code has been prepared for a specific situation, but you can get the position depending on your needs.

draw function not looping as expected

I'm a beginner on here, so apologies in advance for naivety. I've made a simple image on Brackets using Javascript, trying to generate circles with random x and y values, and random colours. There are no issues showing when I open the browser console in Developer Tools, and when I save and refresh, it works. But I was expecting the refresh to happen on a loop through the draw function. Any clues as to where I've gone wrong?
Thanks so much
var r_x
var r_y
var r_width
var r_height
var x
var y
var z
function setup()
{
r_x = random()*500;
r_y = random()*500;
r_width = random()*200;
r_height = r_width;
x = random(1,255);
y= random(1,255);
z= random(1,255);
createCanvas(512,512);
background(255);
}
function draw()
{
ellipse(r_x, r_y, r_width, r_height);
fill(x, y, z);
}
Brackets.io is just your text editor (or IDE if you want to be technical) - so we can remove that from the equation. The next thing that baffles me is that something has to explicitly call your draw() method as well as the setup() method -
I'm thinking that you're working in some sort of library created to simplify working with the Canvas API because in the setup() method you're calling createCanvas(xcord,ycord) and that doesn't exist on it's own. If you want to rabbit hole on that task check out this medium article, it walks you thru all the requirements for creating a canvas element and then drawing on that canvas
Your also confirming that you're drawing at least 1 circle on browser refresh so i think all you need to focus on is 1)initiating your code on load and 2)a loop, and we'll just accept there is magic running in the background that will handle everything else.
At the bottom of the file you're working in add this:
// when the page loads call drawCircles(),
// i changed the name to be more descriptive and i'm passing in the number of circles i want to draw,
// the Boolean pertains to event bubbling
window.addEventListener("load", drawCircles(73), false);
In your drawCircles() method you're going to need to add the loop:
// im using a basic for loop that requires 3 things:
// initialization, condition, evaluation
// also adding a parameter that will let you determine how many circles you want to draw
function drawCircles(numCircles) {
for (let i = 0; i < numCircles; i++) {
ellipse(r_x, r_y, r_width, r_height);
fill(x, y, z);
}
}
here's a link to a codepen that i was tinkering with a while back that does a lot of the same things you are
I hope that helps - good luck on your new learning venture, it's well worth the climb!
Thank you so much for your help! What you say makes sense - I basically deleted the equivalent amount of code from a little training exercise downloaded through coursera, thinking that I could then essentially use it as an empty sandpit to play in. But there's clearly far more going on under the hood!
Thanks again!

Get the position of 3d objects in Facebook AR and changing them via script

I have a 3d object which i want to "move" from A to B via script. I am not too sure how to go about it; I don't understand the Facebook documents. Just a short example as a start would be great.
I assume something along the lines:
var object = Scene.root.find("object");
var lastPosX = object.transform.positionX.lastValue;
object.transform.positionX = //NOT SURE HOW TO PUT THE NEW POSITION
What you need to do is use the AnimationModule - here is a simple example of how to do that:
const Animation = require('Animation');
var obj = Scene.root.find("object");
//set up the length of the animations, 1000 = 1 second
var driver = Animation.timeDriver({durationMilliseconds: 1000});
//define the starting and ending values (start at 0, go to 100)
var sampler = Animation.samplers.linear(0, 100);
//create an animation signal to control the object x position
obj.transform.x = Animation.animate(driver, sampler);
//start the animation
driver.start();
Animation in ARS, like many other things, is based around the concept of "Reactive Programming" and working with "Signals" which are values that change over time. It is essential to get a good grasp of what a signal is and how it works to write useful code in ARS. Read through this for an introductory overview: https://developers.facebook.com/docs/ar-studio/scripting/basics
The above is a very basic example, but there is much more interesting, advanced, and complex effects that you can achieve using the AnimationModule, take a look at the documentation here for more information: https://developers.facebook.com/docs/ar-studio/reference/classes/animationmodule/
Hope this helps!

Convert stroke data to SCG Ink format

I'd like to use Seshat—a handwritten math expression parser—for a project I'm working on, but I'm having some trouble understanding how to provide the program its proper input, an InkML or SCG Ink file.
I've taken a long look at an online example that exists here, and I see that they get a Javascript array of stroke information from an HTML Canvas field with this JS library applied, but I don't know what happens that array after it gets POSTed to their server.
I've read the SCG Ink spec, and I think it might be relatively easy to parse the array into the format, but I'm hoping there's something obvious I'm missing that would make this trivial. Any help would be greatly appreciated.
I emailed the Seshat author and he suggested I convert the input to SCG Ink, which turned out to be pretty easy if you take the JavaScript libraries used at http://cat.prhlt.upv.es/mer/. Specifically, you want jquery.sketchable.memento.min.js, jquery.sketchable.min.js, and jsketch.min.js in addition to regular old jQuery. Here's what I did in case anyone else is interested in Seshat.
Notice from the same page that in main.js they apply the Sketchable library to the HTML canvas area with this block of code:
var $canvas = $('#drawing-canvas').sketchable({
graphics: {
strokeStyle: "red",
firstPointSize: 2
}
});
Now we can take a look at their submitStrokes() function to see how to take the strokes from Sketchable and convert to SCG Ink. The line var strokes = $canvas.sketchable('strokes'); gets the strokes, and then the line strokes = transform(strokes); applies a quick transformation to extract only the data they need. Here's the transform() function for reference:
function transform(strokes) {
for (var i = 0; i < strokes.length; ++i)
for (var j = 0, stroke = strokes[i]; j < stroke.length; ++j)
strokes[i][j] = [ strokes[i][j][0], strokes[i][j][1] ];
return strokes;
};
The value returned fro transform() is a three-dimensional array of strokes and points. (Each element of the first dimension is a stroke, each element of the second dimension is a point, and the third dimension is x-, y-coordinates.) On that site they go ahead and POST that array to the server which must handle the final conversion to SCG Ink. I wrote a JavaScript function to handle it:
function strokesToScg(strokes) {
var scg = 'SCG_INK\n' + strokes.length + '\n'
strokes.forEach(function (stroke) {
scg += stroke.length + '\n'
stroke.forEach(function (p) {
scg += p[0] + ' ' + p[1] + '\n'
})
})
return scg
}
And that's it. The value returned from strokesToScg() is a string describing a series of strokes in the SCG Ink format.

understanding javascript variable handling and referening especially canvas ImageArray and array assigning

consider this code:
var deSaturated = deSaturate(greyscaleCtx.getImageData(0, 0, canvasWidth, canvasHeight));
imageData comes from getImageData canvas function.
function deSaturate (imageData) {
var theData = imageData.data;
var dataLength = theData.length;
var i = dataLength-1;
var lightLevel;
// Iterate through each pixel, desaturating it
while ( i >= 0) {
// To find the desaturated value, average the brightness of the red, green, and blue values
theData[i] = theData[i+1] = theData[i+2] = (theData[i] + theData[i + 1] + theData[i + 2]) / 3;
// Fully opaque
theData[i+3] = 255;
// returning an average intensity of all pixels. Used for calibrating sensitivity based on room light level.
lightLevel += theData[i]; //combining the light level in the samefunction
i -= 4;
}
imageData.data = theData; //bring back theData into imageData.data - do I really need this?
var r = [lightLevel/dataLength,imageData]
return r;
}
during the writing and optimizing of this code I found out I don't really understand how js is treating for example "theData" variable. is working with it just a short way to reference imageData.data in which case I don't need the following code in the end:
imageData.data = theData
but then do I pay in degraded performance ( a lot of DOM I/O)?
or is doing theData = imageData.data actually copying the original array (represented as Uint8ClampedArray) and then I have to reassign the modified data to imageData.data.
I guess this is basic javascript, but I found contradictory code examples in MDN and other developer resources and I would really like to understand this properly.
thanks for the help!
Just ran a quick test:
var idata = ctx.getImageData(0,0,300,300);
var data = idata.data;
for(var i=0;i<data.length;i++){
data[i]=0;
}
ctx.putImageData(idata,0,0);
And that properly blanks out part of the screen as expected. However without putImageData nothing will happen. So changing the data object, whether stored in a different variable or not, will be reflected in that imageData object. However this will not affect the canvas until putImageData has been called.
So, yes, you can remove that final assignment and it will work as desired.
However I will warn that it is not a valid assumption that it is a Uint8ClampedArray. Yes, that is how Chrome handles it (last I checked), and it is indeed what the official specification uses. However some browsers have no notion of Uint8ClampedArray, while still supporting canvas through the now deprecated CanvasPixelArray.
So all you are guaranteed to get is something with the some array-like interface. I had to learn this the hard way when I tried to cache interesting features of image data by creating a new Uint8ClampedArray, which failed in some browsers.
See: https://developer.mozilla.org/en-US/docs/DOM/CanvasPixelArray
In javascript, assigning either an array or an object just assigns a reference to that array or object - it does not make a copy of the data. A copy is only made if you physically create a new array and copy the data over or call some function that is designed to do that for you.
So, if imageData.data is an array, then assigning it to theData just makes a shortcut for referring to the same data. It does not make a new copy of the data. Thus, after modifying the data pointed to by theData, you don't have to assign it back to imageData.data because there is only one copy of the data and both theData and imageData.data point already point to that same copy of the data.
So, in direct answer to your question, this line is unnecessary:
imageData.data = theData;

Categories