Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Canvas: we must go deeper


Published on

  • Be the first to comment

  • Be the first to like this

Canvas: we must go deeper

  1. 1. Canvas: we must go deeper Szymon Piłkowski (freelancer, previously crytek & bigpoint)
  2. 2. Canvas?!The canvas element provides scripts with a resolution-dependent bitmap canvas, which can be used forrendering graphs, game graphics, or other visual imageson the fly.
  3. 3. Canvas is a bitmap• one-dimensional array• [R,G,B,A,// pixel 0,0 R,G,B,A,// pixel 1,0 R,G,B,A,// pixel 2,0 (...) ]• point 0,0 placed in top left corner
  4. 4. Canvas basics• Immediate access (almost)• Low-level API• No scene graph, no direct access to drawn elements• Basic animation = redrawing everything each frame
  5. 5. Drawing on canvas (example from MDN)
  6. 6. Simple Game Loop
  7. 7. Pre-rendering / Buffering• Buffer is a copy of bitmap state (single frame) which is kept in memory• Buffers are known in Computer Graphics for 40 years• Using buffers you’re able to save and restore drawn states• ... and you can use them in JavaScript, too
  8. 8. Buffers in JS• Wrong way:• Slow, slow, slow• still popular
  9. 9. Buffers in JS• Good way context.drawImage: “can take either an HTMLImageElement, an HTMLCanvasElement, or an HTMLVideoElement for the image argument.” (another way: use toDataURL method)• As fast as drawing normal images
  10. 10. Buffers: performance optimisation
  11. 11. Buffers in games(image from isocity by Rob Evans)
  12. 12. Render cycle Background layer (rendered once, never cleared) Static layer (rendered anew when invalidated) Dynamic layer (rendered anew each frame)
  13. 13. Render cycle (code) (needs to be tweaked per game)
  14. 14. Pre-processing sprites• Saving disk space• Saving designers time• Improving the pipeline (from onslaught! arena case study on
  15. 15. Pre-processing sprites
  16. 16. Collision detection• Problem: canvas is just a bitmap.• You can’t attach events to drawn objects• Detecting collision between a point (mouse pointer) and any rendered shape (image or primitive) is not straight-forward
  17. 17. Hitmap / Collision map 1. map objects to unique colors
  18. 18. Hitmap / Collision map 2. store in memory a copy of each object drawn in single color (using composite operations)
  19. 19. Hitmap / Collision map3. when checking collisions, do a single render of candidates to a buffer4. grab color from point and compare with colorMap
  20. 20. end()• questions?••• Thanks!