SlideShare una empresa de Scribd logo
1 de 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

Más contenido relacionado

La actualidad más candente

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
 

La actualidad más candente (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
 

Similar a 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
 

Similar a 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
 
First kinectslides
First kinectslidesFirst kinectslides
First kinectslides
 
cs247 slides
cs247 slidescs247 slides
cs247 slides
 
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?
 

Último

Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 

Último (20)

Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 

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

Notas del editor

  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