SlideShare ist ein Scribd-Unternehmen logo
1 von 29
Pointer v.
 Canvas
Who Are We?




  Dean Hudson, @deanero
Mason Browne, @metapandava
  Developers, Massively Fun
We make games with
open web technology.

http://massivelyfun.com
    @massivelyfun
Basic Game Loop
  and Entities
Game Loop
         Outline
• Call requestAnimationFrame
• Handle queued UI events
• Call update on your game entities
• Render!
// game loop
gameLoop = {
    run: function () {
        this.id = requestAnimationFrame(this.run);
        update(); // Call update on each entity
        draw();   // Call draw on each entity
    },
    stop: function () {
        cancelAnimationFrame(this.id);
    }
};

gameLoop.run();
RAF Shim

• Lots of examples on the internet
• Set RAF to whichever your browser has
• Fallback to set timeout at ~16ms
buildRAFPolyfill = function () {
  window.requestAnimationFrame =
    window.requestAnimationFrame         ||
    window.webkitRequestAnimationFrame   ||
    window.mozRequestAnimationFrame      ||
    window.oRequestAnimationFrame        ||
    window.msRequestAnimationFrame       ||
    function (cb, elt) {
       window.setTimeout(function() {
         cb(+new Date());
       }, 1000 / 60);
    };
}
Simple Game
        Entity

• Respond to update call
• Manage position, height, width
• Attach pointer events here
class GameEntity
  # @params: {rect} The entity's drawing primitive
  constructor: (options = {}) ->
    {x, y, rotation} = options
    @position        = new Position(x, y, rotation)
    @id = options.id ? UUID.generate() # You wa this

  moveTo: (pt) ->
    @position.setXY(pt)

  rotateTo: (rot) ->
    @position.setRotation(rot)

  # Coeff is a multiplier from the timer which we can use to adjust
  # motion to match how far we are off our target frame rate
  update: (tick, coeff) ->
    # do something interesting here.

  contains: (otherX, otherY) ->
    @rect.contains(x, y) if @rect? and @linkedRect

module.exports = GameEntity
Simple Draw
        Primitive
• Respond to draw call
• Manage position, height, width
• Determine containment here (image hit
  detection, for instance)
##
# Rect: Drawing primitive
class Rect
   constructor: (options = {}) ->
     @visible = options?.visible ? true
     @width    = options?.width ? 1
     @height   = options?.height ? 1
     {x, y, rotation} = options
     @position = new Position(x, y, rotation)

  draw: (ctx) ->
    throw new RenderError("Implement Me")

  # Basic, rectangular containment.
  contains: (otherX, otherY) ->
    {x, y} = @position.get()
    (otherX >= x && otherX <= x + @width) and
     (otherY >= y && otherY <= y + @height)

module.exports = Rect
Handling Mouse/
 Touch Events
Strategy
• Attach onFoo to your canvas element
  where Foo is your DOM pointer event
• Build a normalized event from the DOM
  event
• Normalize your page X/Y to canvas X/Y.
• Check for containment in game entities
• Call handler if the entity contains the point
  and the handler exists
Your Friend,
 ImageData
WTF is
         ImageData?
• ImageData is what you get back from a
  getImageData() call
• A single byte Array with ALL your pixel
  data
• Pixel data is stored as R, G, B, A tuples
Single pixel Array
     offsets
   0        1                  2        3

 R        G                  B        A
 8 bits   8 bits             8 bits   8 bits



                   4 bytes
Since ImageData
   acts like a byte
       array....
• We can iterate through the pixels and do
  arithmetic or bitwise manipulation on the
  data.
• Use XOR, NOT, etc. Get weird!
var filter = function (x, y, w, h) {
    if (!this._cache) return;
    var ctx = this._cache.getContext('2d'),
        idata = ctx.getImageData(x, y, w, h),
        i;
    for (i = 0; i < idata.data.length; i++) {
        idata.data[i] = (idata.data[i]++) % 255;
    }
};
var filter = function (x, y, w, h) {
    if (!this._cache) return;
    var ctx = this._cache.getContext('2d'),
        idata = ctx.getImageData(x, y, w, h),
        i;
    for (i = 0; i < idata.data.length; i++) {
        if (! i % 4 === 3) continue;
        idata.data[i] = (idata.data[i]++) % 255;
    }
Hit Detection
What we want
Strategy

• If (x, y) is in the bounding box for the image,
  check pixels.
• getImageData() to get a pixel data array for
  your sprite at pixel x, y.
• Check byte values for pixel.
var isPixelPainted = function (x, y) {
  ctx = this.imageCache;   // this must be a canvas!
  thresh = this.transparencyThreshold || 100;

    // Grab a single pixel at x, y: if the alpha channel is greater
    // than the threshold, we're in business. idata acts like a byte
    // array with each pixel occupying 4 slots (R, G, B , A).
    idata = ctx.getImageData(x, y, 1, 1);
    return idata.data[3] > thresh;
}
DON’T FORGET:
 each idata.data
value is between
     0-255!
Dragging Example
Questions?
Thanks!




  dean@massivelyfun.com, @deanero
mason@massivelyfun.com, @metapandava
       http://massivelyfun.com

Weitere ähnliche Inhalte

Was ist angesagt?

Cheat Sheet for Machine Learning in Python: Scikit-learn
Cheat Sheet for Machine Learning in Python: Scikit-learnCheat Sheet for Machine Learning in Python: Scikit-learn
Cheat Sheet for Machine Learning in Python: Scikit-learnKarlijn Willems
 
Intro to Python (High School) Unit #3
Intro to Python (High School) Unit #3Intro to Python (High School) Unit #3
Intro to Python (High School) Unit #3Jay Coskey
 
Computer graphics
Computer graphics Computer graphics
Computer graphics shafiq sangi
 
Deep learning study 3
Deep learning study 3Deep learning study 3
Deep learning study 3San Kim
 
Pandas Cheat Sheet
Pandas Cheat SheetPandas Cheat Sheet
Pandas Cheat SheetACASH1011
 
Gems of GameplayKit. UA Mobile 2017.
Gems of GameplayKit. UA Mobile 2017.Gems of GameplayKit. UA Mobile 2017.
Gems of GameplayKit. UA Mobile 2017.UA Mobile
 
Effective Numerical Computation in NumPy and SciPy
Effective Numerical Computation in NumPy and SciPyEffective Numerical Computation in NumPy and SciPy
Effective Numerical Computation in NumPy and SciPyKimikazu Kato
 
Introduction to NumPy (PyData SV 2013)
Introduction to NumPy (PyData SV 2013)Introduction to NumPy (PyData SV 2013)
Introduction to NumPy (PyData SV 2013)PyData
 
MIDP: Form Custom and Image Items
MIDP: Form Custom and Image ItemsMIDP: Form Custom and Image Items
MIDP: Form Custom and Image ItemsJussi Pohjolainen
 
NTU ML TENSORFLOW
NTU ML TENSORFLOWNTU ML TENSORFLOW
NTU ML TENSORFLOWMark Chang
 
Pythonbrasil - 2018 - Acelerando Soluções com GPU
Pythonbrasil - 2018 - Acelerando Soluções com GPUPythonbrasil - 2018 - Acelerando Soluções com GPU
Pythonbrasil - 2018 - Acelerando Soluções com GPUPaulo Sergio Lemes Queiroz
 
Computer graphics lab manual
Computer graphics lab manualComputer graphics lab manual
Computer graphics lab manualUma mohan
 
Gentlest Introduction to Tensorflow
Gentlest Introduction to TensorflowGentlest Introduction to Tensorflow
Gentlest Introduction to TensorflowKhor SoonHin
 
Python Pandas for Data Science cheatsheet
Python Pandas for Data Science cheatsheet Python Pandas for Data Science cheatsheet
Python Pandas for Data Science cheatsheet Dr. Volkan OBAN
 

Was ist angesagt? (20)

Cheat Sheet for Machine Learning in Python: Scikit-learn
Cheat Sheet for Machine Learning in Python: Scikit-learnCheat Sheet for Machine Learning in Python: Scikit-learn
Cheat Sheet for Machine Learning in Python: Scikit-learn
 
Python book
Python bookPython book
Python book
 
Intro to Python (High School) Unit #3
Intro to Python (High School) Unit #3Intro to Python (High School) Unit #3
Intro to Python (High School) Unit #3
 
Computer graphics
Computer graphics Computer graphics
Computer graphics
 
Numpy python cheat_sheet
Numpy python cheat_sheetNumpy python cheat_sheet
Numpy python cheat_sheet
 
Deep learning study 3
Deep learning study 3Deep learning study 3
Deep learning study 3
 
Cgm Lab Manual
Cgm Lab ManualCgm Lab Manual
Cgm Lab Manual
 
Pandas Cheat Sheet
Pandas Cheat SheetPandas Cheat Sheet
Pandas Cheat Sheet
 
Gems of GameplayKit. UA Mobile 2017.
Gems of GameplayKit. UA Mobile 2017.Gems of GameplayKit. UA Mobile 2017.
Gems of GameplayKit. UA Mobile 2017.
 
Effective Numerical Computation in NumPy and SciPy
Effective Numerical Computation in NumPy and SciPyEffective Numerical Computation in NumPy and SciPy
Effective Numerical Computation in NumPy and SciPy
 
Cpp tutorial
Cpp tutorialCpp tutorial
Cpp tutorial
 
Introduction to NumPy (PyData SV 2013)
Introduction to NumPy (PyData SV 2013)Introduction to NumPy (PyData SV 2013)
Introduction to NumPy (PyData SV 2013)
 
MIDP: Form Custom and Image Items
MIDP: Form Custom and Image ItemsMIDP: Form Custom and Image Items
MIDP: Form Custom and Image Items
 
NTU ML TENSORFLOW
NTU ML TENSORFLOWNTU ML TENSORFLOW
NTU ML TENSORFLOW
 
Pythonbrasil - 2018 - Acelerando Soluções com GPU
Pythonbrasil - 2018 - Acelerando Soluções com GPUPythonbrasil - 2018 - Acelerando Soluções com GPU
Pythonbrasil - 2018 - Acelerando Soluções com GPU
 
Computer graphics lab manual
Computer graphics lab manualComputer graphics lab manual
Computer graphics lab manual
 
NumPy/SciPy Statistics
NumPy/SciPy StatisticsNumPy/SciPy Statistics
NumPy/SciPy Statistics
 
Gentlest Introduction to Tensorflow
Gentlest Introduction to TensorflowGentlest Introduction to Tensorflow
Gentlest Introduction to Tensorflow
 
Python Pandas for Data Science cheatsheet
Python Pandas for Data Science cheatsheet Python Pandas for Data Science cheatsheet
Python Pandas for Data Science cheatsheet
 
Scala.io
Scala.ioScala.io
Scala.io
 

Ähnlich wie Pointer Events in Canvas

Stupid Canvas Tricks
Stupid Canvas TricksStupid Canvas Tricks
Stupid Canvas Tricksdeanhudson
 
Is HTML5 Ready? (workshop)
Is HTML5 Ready? (workshop)Is HTML5 Ready? (workshop)
Is HTML5 Ready? (workshop)Remy Sharp
 
Is html5-ready-workshop-110727181512-phpapp02
Is html5-ready-workshop-110727181512-phpapp02Is html5-ready-workshop-110727181512-phpapp02
Is html5-ready-workshop-110727181512-phpapp02PL dream
 
JavaScript Advanced - Useful methods to power up your code
JavaScript Advanced - Useful methods to power up your codeJavaScript Advanced - Useful methods to power up your code
JavaScript Advanced - Useful methods to power up your codeLaurence Svekis ✔
 
Scaling Deep Learning with MXNet
Scaling Deep Learning with MXNetScaling Deep Learning with MXNet
Scaling Deep Learning with MXNetAI Frontiers
 
Snake in the DOM!
Snake in the DOM!Snake in the DOM!
Snake in the DOM!Gil Steiner
 
How to make a video game
How to make a video gameHow to make a video game
How to make a video gamedandylion13
 
Need an detailed analysis of what this code-model is doing- Thanks #St.pdf
Need an detailed analysis of what this code-model is doing- Thanks #St.pdfNeed an detailed analysis of what this code-model is doing- Thanks #St.pdf
Need an detailed analysis of what this code-model is doing- Thanks #St.pdfactexerode
 
SenchaCon 2016: Add Magic to Your Ext JS Apps with D3 Visualizations - Vitaly...
SenchaCon 2016: Add Magic to Your Ext JS Apps with D3 Visualizations - Vitaly...SenchaCon 2016: Add Magic to Your Ext JS Apps with D3 Visualizations - Vitaly...
SenchaCon 2016: Add Magic to Your Ext JS Apps with D3 Visualizations - Vitaly...Sencha
 
need help with code I wrote. This code is a maze gui, and i need hel.pdf
need help with code I wrote. This code is a maze gui, and i need hel.pdfneed help with code I wrote. This code is a maze gui, and i need hel.pdf
need help with code I wrote. This code is a maze gui, and i need hel.pdfarcotstarsports
 
Browsers with Wings
Browsers with WingsBrowsers with Wings
Browsers with WingsRemy Sharp
 
Th 0230 turbo_chargeyourui-howtomakeyourandroidu_ifastandefficient
Th 0230 turbo_chargeyourui-howtomakeyourandroidu_ifastandefficientTh 0230 turbo_chargeyourui-howtomakeyourandroidu_ifastandefficient
Th 0230 turbo_chargeyourui-howtomakeyourandroidu_ifastandefficientBin Shao
 

Ähnlich wie Pointer Events in Canvas (20)

Stupid Canvas Tricks
Stupid Canvas TricksStupid Canvas Tricks
Stupid Canvas Tricks
 
Real life XNA
Real life XNAReal life XNA
Real life XNA
 
Is HTML5 Ready? (workshop)
Is HTML5 Ready? (workshop)Is HTML5 Ready? (workshop)
Is HTML5 Ready? (workshop)
 
Is html5-ready-workshop-110727181512-phpapp02
Is html5-ready-workshop-110727181512-phpapp02Is html5-ready-workshop-110727181512-phpapp02
Is html5-ready-workshop-110727181512-phpapp02
 
cs247 slides
cs247 slidescs247 slides
cs247 slides
 
First kinectslides
First kinectslidesFirst kinectslides
First kinectslides
 
JavaScript Advanced - Useful methods to power up your code
JavaScript Advanced - Useful methods to power up your codeJavaScript Advanced - Useful methods to power up your code
JavaScript Advanced - Useful methods to power up your code
 
Scaling Deep Learning with MXNet
Scaling Deep Learning with MXNetScaling Deep Learning with MXNet
Scaling Deep Learning with MXNet
 
Snake in the DOM!
Snake in the DOM!Snake in the DOM!
Snake in the DOM!
 
Game age ppt
Game age pptGame age ppt
Game age ppt
 
How to make a video game
How to make a video gameHow to make a video game
How to make a video game
 
Need an detailed analysis of what this code-model is doing- Thanks #St.pdf
Need an detailed analysis of what this code-model is doing- Thanks #St.pdfNeed an detailed analysis of what this code-model is doing- Thanks #St.pdf
Need an detailed analysis of what this code-model is doing- Thanks #St.pdf
 
ES6(ES2015) is beautiful
ES6(ES2015) is beautifulES6(ES2015) is beautiful
ES6(ES2015) is beautiful
 
SenchaCon 2016: Add Magic to Your Ext JS Apps with D3 Visualizations - Vitaly...
SenchaCon 2016: Add Magic to Your Ext JS Apps with D3 Visualizations - Vitaly...SenchaCon 2016: Add Magic to Your Ext JS Apps with D3 Visualizations - Vitaly...
SenchaCon 2016: Add Magic to Your Ext JS Apps with D3 Visualizations - Vitaly...
 
need help with code I wrote. This code is a maze gui, and i need hel.pdf
need help with code I wrote. This code is a maze gui, and i need hel.pdfneed help with code I wrote. This code is a maze gui, and i need hel.pdf
need help with code I wrote. This code is a maze gui, and i need hel.pdf
 
การทำหิมะตกใน Flash
การทำหิมะตกใน Flashการทำหิมะตกใน Flash
การทำหิมะตกใน Flash
 
Browsers with Wings
Browsers with WingsBrowsers with Wings
Browsers with Wings
 
Th 0230 turbo_chargeyourui-howtomakeyourandroidu_ifastandefficient
Th 0230 turbo_chargeyourui-howtomakeyourandroidu_ifastandefficientTh 0230 turbo_chargeyourui-howtomakeyourandroidu_ifastandefficient
Th 0230 turbo_chargeyourui-howtomakeyourandroidu_ifastandefficient
 
Intro to HTML5 Canvas
Intro to HTML5 CanvasIntro to HTML5 Canvas
Intro to HTML5 Canvas
 
A More Flash Like Web?
A More Flash Like Web?A More Flash Like Web?
A More Flash Like Web?
 

Kürzlich hochgeladen

Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 

Kürzlich hochgeladen (20)

Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 

Pointer Events in Canvas

  • 2. Who Are We? Dean Hudson, @deanero Mason Browne, @metapandava Developers, Massively Fun
  • 3. We make games with open web technology. http://massivelyfun.com @massivelyfun
  • 4.
  • 5. Basic Game Loop and Entities
  • 6. Game Loop Outline • Call requestAnimationFrame • Handle queued UI events • Call update on your game entities • Render!
  • 7. // game loop gameLoop = { run: function () { this.id = requestAnimationFrame(this.run); update(); // Call update on each entity draw(); // Call draw on each entity }, stop: function () { cancelAnimationFrame(this.id); } }; gameLoop.run();
  • 8. RAF Shim • Lots of examples on the internet • Set RAF to whichever your browser has • Fallback to set timeout at ~16ms
  • 9. buildRAFPolyfill = function () { window.requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (cb, elt) { window.setTimeout(function() { cb(+new Date()); }, 1000 / 60); }; }
  • 10. Simple Game Entity • Respond to update call • Manage position, height, width • Attach pointer events here
  • 11. class GameEntity # @params: {rect} The entity's drawing primitive constructor: (options = {}) -> {x, y, rotation} = options @position = new Position(x, y, rotation) @id = options.id ? UUID.generate() # You wa this moveTo: (pt) -> @position.setXY(pt) rotateTo: (rot) -> @position.setRotation(rot) # Coeff is a multiplier from the timer which we can use to adjust # motion to match how far we are off our target frame rate update: (tick, coeff) -> # do something interesting here. contains: (otherX, otherY) -> @rect.contains(x, y) if @rect? and @linkedRect module.exports = GameEntity
  • 12. Simple Draw Primitive • Respond to draw call • Manage position, height, width • Determine containment here (image hit detection, for instance)
  • 13. ## # Rect: Drawing primitive class Rect constructor: (options = {}) -> @visible = options?.visible ? true @width = options?.width ? 1 @height = options?.height ? 1 {x, y, rotation} = options @position = new Position(x, y, rotation) draw: (ctx) -> throw new RenderError("Implement Me") # Basic, rectangular containment. contains: (otherX, otherY) -> {x, y} = @position.get() (otherX >= x && otherX <= x + @width) and (otherY >= y && otherY <= y + @height) module.exports = Rect
  • 15. Strategy • Attach onFoo to your canvas element where Foo is your DOM pointer event • Build a normalized event from the DOM event • Normalize your page X/Y to canvas X/Y. • Check for containment in game entities • Call handler if the entity contains the point and the handler exists
  • 17. WTF is ImageData? • ImageData is what you get back from a getImageData() call • A single byte Array with ALL your pixel data • Pixel data is stored as R, G, B, A tuples
  • 18. Single pixel Array offsets 0 1 2 3 R G B A 8 bits 8 bits 8 bits 8 bits 4 bytes
  • 19. Since ImageData acts like a byte array.... • We can iterate through the pixels and do arithmetic or bitwise manipulation on the data. • Use XOR, NOT, etc. Get weird!
  • 20. var filter = function (x, y, w, h) { if (!this._cache) return; var ctx = this._cache.getContext('2d'), idata = ctx.getImageData(x, y, w, h), i; for (i = 0; i < idata.data.length; i++) { idata.data[i] = (idata.data[i]++) % 255; } };
  • 21. var filter = function (x, y, w, h) { if (!this._cache) return; var ctx = this._cache.getContext('2d'), idata = ctx.getImageData(x, y, w, h), i; for (i = 0; i < idata.data.length; i++) { if (! i % 4 === 3) continue; idata.data[i] = (idata.data[i]++) % 255; }
  • 24. Strategy • If (x, y) is in the bounding box for the image, check pixels. • getImageData() to get a pixel data array for your sprite at pixel x, y. • Check byte values for pixel.
  • 25. var isPixelPainted = function (x, y) { ctx = this.imageCache; // this must be a canvas! thresh = this.transparencyThreshold || 100; // Grab a single pixel at x, y: if the alpha channel is greater // than the threshold, we're in business. idata acts like a byte // array with each pixel occupying 4 slots (R, G, B , A). idata = ctx.getImageData(x, y, 1, 1); return idata.data[3] > thresh; }
  • 26. DON’T FORGET: each idata.data value is between 0-255!
  • 29. Thanks! dean@massivelyfun.com, @deanero mason@massivelyfun.com, @metapandava http://massivelyfun.com

Hinweis der Redaktion

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n