Processing: how can shapes form a text? - javascript

i wonder how this is made: http://workshop.chromeexperiments.com/examples/gui/#1--Basic-Usage
Those spots form a text and when clicked , they explode.
How can shapes form a text? Can i achieve this with processing.js?
Thanks.

I guess one way is to have a model for each character. For example, manually create the letter 'A' via shapes. Then for each letter in the message, you would display the character model for the letters

I'm not sure if you want to write this in processing or in javascript. This is a javascript library, so you can use it in a javascript context. To make it on processing and use processingjs to display it on web you got to use processing resources to achieve the same result or manage to pass data from/to javascript and processing. There is this example from processingjs site on connecting your page with a processing sketch. Note that processingjs does not support use of processing libraries, so you can't use any of Precessing typography libraries in this workflow. I think that they could be very handy though...
As how doing this on processing, i think i would go for drawing letters in a not displayed PGraphics, and using a pixel color test on this surface to drive the drawings of the circles. This would allow to alter the text in run time. Like, in pseudo code
PGraphics matteImage = new PGraphics(size, size, render);//
matteImage.background(black);
matteImage.fill(255);
matteImage.text("A", x,y);
matteImage.loadPixels();
for(i; i < matteImage.length;i++)
{
color c = matteImage.pixels[i];
if ( c == white)
{
doDrawEllipses();
}
}
In drawing circles method/class i would add some noise/randomness, exploding handle...

Related

How to apply transformation to selection in Illustrator by scripting

I managed to select every thing I want in Illustrator with a ExtendScript Toolkit javascript code: lots of things (text, path, symbols, ...) in several layers. Now I want to resize them the same way, then move them.
I know how to apply a transformation to one object by code, but I want to avoid looping on each element because it would be very very long and transformation would be applied from the anchor point of each element, so my drawings wouldn't be cohesive.
So, I am looking for a way to do like in Illustrator UI: right click > transform > scale. Is there any UI command like this I could access from code (javascript)?
There are at least three ways to do this:
Record AI Actions that perform required transformations, and then play these Actions (by DoScript) from your script
Group selected objects and apply required transformations to the group as #Dane proposed. You need to backup the Layer object property to allow objects to be restored in original layers, as shown in VBA example below:
For i = Index_Lo To Index_Hi
Call Layers_Backup.Add(Item:=SelectedItems(i).Layer, Key:=Format(i))
Call SelectedItems(i).Move(Temp_Group, AiElementPlacement.aiPlaceAtEnd)
Next i
Call Temp_Group.Resize(scaleX:=120, scaleY:=120, changeLineWidths:=120)
For i = Index_Lo To Index_Hi
Call SelectedItems(i).Move(Layers_Backup(Format(i)), AiElementPlacement.aiPlaceAtEnd)
Next i
Call Windows API functions (like PostMessage (..., WM_COMMAND, ..., ...), SendDlgItemMessage, FindWindowEx etc) to show, fill and execute required AI transformations dialog boxes
IMHO, item #1 is the easiest to implement while item#2 is the most reliable
So I dont know if you can get away with not looping in some form or other. that said, if you dont mind putting your selection in to a group, it might be faster to loop through your selection adding to a group which might be faster than looping and through the selection and scale and moving each element. With the group object you can then do groupObject.scale() and .translate().
Here is a snippet i took from a script of mine.
#target "illustrator"
var aiApp = app.activeDocument;
var aSelection = aiApp.selection;
var aGroup = app.activeDocument.groupItems.add();
for (i=0; i < aSelection.length; i++){
aSelection[i].move( aGroup, ElementPlacement.INSIDE);
aSelection[i].move( aGroup, ElementPlacement.PLACEATEND);
}
//moves up 700 points and scales by 200
aGroup.translate(0,700)
aGroup.resize(200, 200, true , true, true, true, 200)

JavaScript: How do i use a string as a piece of code

I am making a simple-ish graph maker to visualise equations. I need to be able to have the user input a string in a textbox and then interpret that as a piece of code I can execute to produce the graph. The way I am displaying the graph is by going through x in small increments and using an equation to then calculate the y position and then drawing a line between the points. At the moment I am just manually making a function in the code for example:
function(val) { return (val * val) + 5; }
but I need to be able to create a similar function from a string so the user could just input something like "(x*x)+(2*x)". is there any way to do this?
Canonically, this is done with eval(), although it comes with many caveats and should probably be avoided.
There are several questions on SO that discuss eval alternatives, but in your case, I would suggest a very bare-bones parser -- especially if all you're handling are mathematical equations.

How To Change the turn in chessboard.js?

I am working in chessboard.js for creating a multyplayer chessboard using signalR.
but i am having a problem in player movement.
what i am doing is sending the FEN string from client1 to client2.and Thus client2 represent that FEN string on board.
Now the problem is that the player2 represent the FEN on Board but player turn is not changed by FEN.
So both Player 1 and 2 move white first then black secondly.and that is not to be supposed.
i want Player1 moves from white side.His FEN is send To Player2.then Player2 will Move with Black Color (but currently player2 move with white which is error).
So please help me how to change the turn of player1 or player2 forcely.
I was struggling with the same issue when creating a similar multiplayer chess game using chessboard.js along with chess.js (the engine running the actual game rules)
The answer lies within the chess.js file that is referenced on the chessboard.js api documentation.
Line 157 of chess.js has this:
var turn = WHITE;
If you wish to change the turn of the whole game you can simply do this:
turn = BLACK;
turn = WHITE;
turn = "w";
turn = "b";
Any of them will work. I also created a convenience function that can be more easily used by other scripts which adds setTurn() and turn() to the public API..
Convenience function to add to API for turn manipulation:
Around line 1115 of chess.js (not chessboard.js), you will find a function that starts off with:
return {
/***************************************************************************
* PUBLIC CONSTANTS (is there a better way to do this?)
**************************************************************************
I simply added The following to right below the comment:
turn: function() {
return turn;
},
setTurn: function(newTurn) {
turn = newTurn;
},
The result is that now from either any instance of chess.js
(default name is game), you can simply change turns like this:
game.setTurn("b");
game.setTurn("w");
This is but one hurdle that I ran into while making a multiplayer version. The next hurdle you will likely face is going to be: what happens if a player gets disconnected or doesn't respond? How about if they inject a JS file into the page that allows them to change turns at will? These issues will be more of a pain to solve. Also look out for other types of injection attacks such as manipulation of the game FEN externally.
Good luck!
Leave comment if you want me to share my source code -- I figured out most of the issues that come up with chessboard.js as multiplayer.

Drawing plots interactively in a web app

I am looking for a library preferably in JavaScript, that will allow a user to draw a plot (simple one consisting of vertical and horizontal steps) like this one:
The idea is that when the user is done with the plot I can generate data points from the graph and process them.
I don't know where to start, I am looking to start learning to do this within a JS based framework (meteor) but I can't find a library that allows for something like this. The closest library I found is d3.js but I couldn't find any example that allows for this.
Would anyone be able to point out to me a sample example to start from? Would you know of a better suited library to accomplish what I am asking for?
Here is a relatively simple fiddle which accomplishes some of what you asked for, excluding axis (which are relatively easy and has plenty of examples). It uses D3 for all the drawing and mouse event handling. On click it simply executes svg.append("circle").attr("r", 5), and if it's not the first click (i.e. linking points) then it also will create a path element using the previous mouse click coordinates:
svg.insert("path", "circle").attr("d", function () {
return [
"M", prevClickLoc[0], prevClickLoc[1],
"L", prevClickLoc[0], y,
"L", x, y].join(" ");
})
Where x and y are the current mouse coordinates. Also has an export button that will output a list in the form of cx,cy,cx,cy,... :: d,d,d,d,.... On import, you could easily split this array into two using indexOf("::") or whatever you choose if you want to change the formatting. Then just exectue for (x in circles) {svg.append("circle").attr("cx", function...).attr("cy", function...);} and do something similar for paths for (y in paths) {svg.append("path").attr("d", function(){return paths[y];});}. It would be even easier if on export you made the cxcy array in the format cx;cy,cx;cy since then you could simply split the array at each comma and then split each index of the resulting array at the semicolon for a nice nested array.
Small update in this version, you can only place points if the current mouse x is greater than the previous x coordinate, and it also has the line d3.event.stopPropagation(); which prevents accidental highlighting of the page.

Embed text into PNG

I'm looking for a tool that'd let me embed json-formatted information inside a PNG -file.
This far it's been quite quiet. Do I have to write it myself?
I'd be especially interested of doing it with javascript. Into an image I extract from a canvas with toDataURL -method.
If you want to embed text you may want to look at this in particular, which comes from the PNG specification. It seems a little on the complicated side.
The "easy" steganographic method looks a little more simple.
What may actually be better suited for your purpose is to create a javascript object that contains the image data and the JSON data - then just pass that object around wherever you need it.
I am completely unfamiliar with Python, however if you can access any of the prominent image processing libraries it is possible.
Take a look here for ImageMagick<->Python solutions.
Edit
You may wish to take a look at this blog post for information regarding steganography (hiding information within an image) and an offshoot of the ImageMagick library. It uses C++ here but I'm sure you could figure out a way to incorporate the base processes in Python.
Hmm, here’s a partial libpng implementation in JS: http://www.xarg.org/download/pnglib.js.
Copying another answer of mine in another question:
Here's an old not too-fancy module I did for a friend once (Python 2.x code):
the code
from __future__ import division
import math, os, array, random
import itertools as it
import Image as I
import sys
def encode(txtfn, imgfn):
with open(txtfn, "rb") as ifp:
txtdata= ifp.read()
txtdata= txtdata.encode('zip')
img= I.open(imgfn).convert("RGB")
pixelcount= img.size[0]*img.size[1]
## sys.stderr.write("image %dx%d\n" % img.size)
factor= len(txtdata) / pixelcount
width= int(math.ceil(img.size[0]*factor**.5))
height= int(math.ceil(img.size[1]*factor**.5))
pixelcount= width * height
if pixelcount < len(txtdata): # just a sanity check
sys.stderr.write("phase 2, %d bytes in %d pixels?\n" % (len(txtdata), pixelcount))
sys.exit(1)
## sys.stderr.write("%d bytes in %d pixels (%dx%d)\n" % (len(txtdata), pixelcount, width, height))
img= img.resize( (width, height), I.ANTIALIAS)
txtarr= array.array('B')
txtarr.fromstring(txtdata)
txtarr.extend(random.randrange(256) for x in xrange(len(txtdata) - pixelcount))
newimg= img.copy()
newimg.putdata([
(
r & 0xf8 |(c & 0xe0)>>5,
g & 0xfc |(c & 0x18)>>3,
b & 0xf8 |(c & 0x07),
)
for (r, g, b), c in it.izip(img.getdata(), txtarr)])
newimg.save(os.path.splitext(imgfn)[0]+'.png', optimize=1, compression=9)
def decode(imgfn, txtfn):
img= I.open(imgfn)
with open(txtfn, 'wb') as ofp:
arrdata= array.array('B',
((r & 0x7) << 5 | (g & 0x3) << 3 | (b & 0x7)
for r, g, b in img.getdata())).tostring()
findata= arrdata.decode('zip')
ofp.write(findata)
if __name__ == "__main__":
if sys.argv[1] == 'e':
encode(sys.argv[2], sys.argv[3])
elif sys.argv[1] == 'd':
decode(sys.argv[2], sys.argv[3])
the algorithm
It stores a byte of data per image pixel using: the 3 least-significant bits of the blue band, the 2 LSB of the green one and the 3 LSB of the red one.
encode function: An input text file is compressed by zlib, and the input image is resized (keeping proportions) to ensure that there are at least as many pixels as compressed bytes. A PNG image with the same name as the input image (so don't use a ".png" filename as input if you leave the code as-is :) is saved containing the steganographic data.
decode function: The previously stored zlib-compressed data are extracted from the input image, and saved uncompressed under the provided filename.
I verified the old code still runs, so here's an example image containing steganographic data:
You'll notice that the noise added is barely visible.
You can use the recently released JavaScript library steganography.js. Have a look at the showcase and the documentation for the basic usage.
The library makes use of a HTML canvas and embeds the information in the alpha channel of the image. Basically you just need to use steg.encode(message, image) and pass the JSON-data (as string) as message and the image as dataURL. To read this information from the image use steg.decode(image) and pass the image as dataURL again.
After reading the information again you get the JSON-data as string so you will have to parse it to a JavaScript object again. So besides the parsing from/to string I hope it fits your requirements.
The answers here have seriously over-engineered the question. I am sorry you had to wait 11 years for the answer. The ability to do this is standard and part of the PNG spec. Tons of apps use this today.
You can drop JSON or any other data right into PNGs. You can do this in like 3 lines of JavaScript with the npm "png-chunk-text" (https://www.npmjs.com/package/png-chunk-text)
Now you can read and write JSON inside of PNGs at lightning speed and it took you 30 seconds to develop it, and the process is standard, i.e., other tools can read it too.
Someone has already attempted to embed a Mario-like platformer game in a PNG image. Using getImageData is the key to reading out the data; the object that that method returns gives a one-dimensional array holding the individual RGBA values of each pixel.
Note that this does not "hide" the data within the area that the user sees, but you could probably use a CSS sprite like technique (or "crop" the image using multiple canvases) to show only the part of a combined image you want to.
Why not just use this tool?
http://www.jsclasses.org/package/324-JavaScript-Embed-encoded-text-in-images-using-steganography.html
and here on github:
https://github.com/blauharley/LoremImageCryptonator
It's a normal object that can be used for embedding text into each color-channel(red, green...).
When embedding text into the alpha-channel there should not be as much noise as embedding text on other color-channels, so you should not see any difference before and after inserting text into an image.

Categories

Resources