SlideShare uma empresa 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

Mais conteúdo relacionado

Mais procurados

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
 

Mais procurados (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
 

Semelhante 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
 

Semelhante 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
 
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?
 

Último

Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
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
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
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
 
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
 
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
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
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
 

Último (20)

Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
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
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
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
 
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
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
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
 

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 do 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