rezoner / CanvasQuery

Canvas for 2d gamedevelopers. Out of box canvas, keyboard, mouse, events.
http://canvasquery.com
586 stars 52 forks source link

Align #35

Closed rezoner closed 9 years ago

rezoner commented 9 years ago

Not really sure how would it work without CPU overhead but I think

this.layer.align(0.5, 0.5)

would be awesome.

It would affect drawImage, drawRegion, paths auto-magically centering them upon desired point.

rezoner commented 9 years ago

In particualar I am nervously looking to replace the pattern that happens 24/7 in my code.

This is how you draw a centered image:

app.layer
  .save();
  .translate(100, 100));
  .rotate(0.5 * Math.PI);
  .scale(0.6, 0.6);
  .drawImage(image, -image.width / 2, -image.height /2);
  .restore();
rezoner commented 9 years ago

First iteration - introducing align:

This is how you draw a centered image:

app.layer
  .align(100, 100, 0.5, 0.5)
  .rotate(0.5 * Math.PI)
  .scale(0.6, 0.6)
  .drawImage(image, 0, 0)
  .restore();

Essentials

app.layer
  .save()
  .translate(100, 100)
  .drawImage(image, -image.width / 2, -image.height /2)
  .restore();

/* equals to */

app.layer
  .align(100, 100, 0.5, 0.5)
  .drawImage(image, 0, 0)
  .restore();

On a side note - I have also managed to decrease performance loss over raw canvas from 20% to 9%

feiss commented 9 years ago

looks great, the only issue I see here is that the programmer must know that a save() is being done, and he should do a restore() afterwards.

Also, someone could ask if there's a way to assure pixel perfect drawing (is there a floor() inside align?)

anyway, big fan of this align()

rezoner commented 9 years ago

How about:

align

app.layer.save()
  .translate(x, y)
  .align(0.5, 0.5)
  .rotate(0.5)
  .scale(1.0, 1.0)
  .drawImage(image, 0, 0)
  .restore();

(because I find save and translate in align a bit shady)

stars = save, translate, align, rotate, scale

app.layer
  .stars(100, 100, 0.5, 0.5, 0.4, 1.0)
  .drawImage(image, 0, 0)
  .restore();
feiss commented 9 years ago

Nice, and undefined parameters could default to (0,0,0,0,0,1), so you could do stars(100,100) just to translate, stars(100,100,0.5,0.5,0.4) to rotate around center but not scale, etc..

clean and handy, do you like it?

rezoner commented 9 years ago

Yesh I do.

I guess align in the end would make more sense as you usually want to have just 0.5, 0.5

But then STARS makes it easy to remember the arguments order.

feiss commented 9 years ago

And you can sell it well: "Now with a brand new STARS operator!"

Powerful shit.

rezoner commented 9 years ago

Pushed online

https://twitter.com/rezoner/status/562921309890703360