-
• #2
var p = [0,0,0,50,50,50]; function translate(tx, ty, p) { return p.map((x, i)=> x+((i%2)?ty:tx)); } function scale(sx, sy, p) { return p.map((x, i) => x*((i % 2) ? sy : sx)); } g.clear(); g.drawPoly(p,1); g.drawPoly(translate(50,0,p.slice()),1); g.drawPoly(translate(50,50,scale(2,2,p.slice())),1);
Keep in mind that this allocates a new array every time. Easier to reason about IMO, but don't allocate a lot, if you are low on memory.
And of course you can do it in a one-liner:
var translate = (tx, ty, p) => p.map((x, i)=> x + ((i % 2) ? ty : tx)); var scale = (sx, sy, p) => p.map((x, i) => x * ((i % 2) ? sy : sx));
-
• #3
That was quick - Thanks , I prefer the one-liner ;-)
Keep in mind that this allocates a new array every time
Else you modify array p[] , or am I missing something here?
-
• #4
Yes, foreach, for loop modifies the array in place (ok, you can create a new array, but usually you don't). Just console.log out after each call to compare the different ways.
-
• #5
...instead of using terniary if-then-else construct and or modulo
index % 2
for x/y base or offset access when provided as array[x,y]
, you can also useindex & 1
- since index is an int after all.Nice to use
.slice()
with no args for creating a copy! Like it! -
• #6
I guess this is even quicker than module, thanks 😊
-
• #7
Right now,
fillPoly
anddrawPoly
just iterate over the array they're given, but I guess they could be modified to take data of the form[[x,y],[x,y]...]
or[{x,y},{x,y},...]
? It might make this sort of thing a bit more readable? -
• #8
Multiple arrays to draw more than one Poly with a single call would be nice too.
-
• #9
I know why leaving out the array completely is not on the list: limit of number of arguments... On the other hand to have extra packaging around the data is like going to produce store and find every cherry in it's own package even though many being twins or triplets by stem... ;-). With scares resources I'm totally fine with single level array packaging... for simple polygons though I could well live w/ just plain 'naked' arguments. For places where that is so - such as the rectangle - I still can do it data driven w/ single 'object' by usine
g.fillRect.apply(g,extentArray);
.For polygon I could see the close information being in the last array element... But thinking about why I would like to have that and how I would use and construct it, it is not worth further pursuit (to go o-o for shapes, the shape info would be missed and needed as well to be included... For that I can then either make a real object w/ properties, such as: shape:, vertices:, closed:, or with arrays as object crutches, [shapeTypeValue,[verticesValues,...],closedValue].
Hi,
can p.map() be used to translate, scale or rotate points in an array with the corresponding function?
For now I use something like this, but prefer to use . map.
Any suggestion how to use .map to do the job?
1 Attachment