Empowering Africa's Next Generation: The AI Leadership Blueprint
Canvas: we must go deeper
1. Canvas: we must go deeper
Szymon Piłkowski
(freelancer, previously crytek & bigpoint)
http://twitter.com/ard
2. Canvas?!
The canvas element provides scripts with a resolution-
dependent bitmap canvas, which can be used for
rendering graphs, game graphics, or other visual images
on the fly.
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. Canvas basics
• Immediate access (almost)
• Low-level API
• No scene graph, no direct access to drawn elements
• Basic animation = redrawing everything each frame
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. Buffers in JS
• Wrong way:
• Slow, slow, slow
• still popular
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
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
18. Hitmap / Collision map
2. store in memory a copy of each
object drawn in single color (using
composite operations)
19. Hitmap / Collision map
3. when checking collisions, do a single render
of candidates to a buffer
4. grab color from point and compare with
colorMap