SlideShare ist ein Scribd-Unternehmen logo
1 von 49
Stupid Canvas
    Tricks
Who Am I?




 Dean Hudson, @deanero
Bit Twiddler at Massively Fun
We make games with
open web technology.
    We’re hiring!
What this is?

• Tips tricks and about the Canvas API
• 2D Context
• Focus on game programming
• Focus on bitmaps
• Me v. Me Lightning Talks
What this isn’t

• A talk about WebGL
• Terribly deep on any one topic
• A JavaScript or Canvas API tutorial
But first: the
dumbest trick I
could think of
Pro Tip: Use HSL
 instead of RGB
      when
  interpolating
      color.
1) Basic Tools
A Simple
Animation Loop
Outline

• Call requestAnimationFrame
• Handle queued UI events
• Call update on your game entities
• Render!
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();
        draw();
    },
    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);
    };
}
Profiling
chrome://tracing

• Wrap things you care about in
  console.time() / console.timeEnd() calls
• Bring up tracing in a tab
• Downside: console spam
var profile = function (name, cb) {
  console.time(name);
  cb();
  console.timeEnd(name);
}

// then later...
profile('render', function () {
  // my render call.
  render();
});
Testing?
Testing Canvas is
       hard.

• PhantomJS (A little scary...)
• Stub out the Canvas API
Testing Canvas is
       hard.

• PhantomJS (A little scary...)
• Stub out the Canvas API
2) Caching Tricks
Basic Technique
• Create a canvas element in your code
• Get its context
• Write pixels to that context
• Use the canvas in a drawImage() call on
  another canvas context
• YOU DON’T ADD THE CACHED CANVAS
  TO THE DOM!
var canvasCache = document.createElement('canvas'),
    cacheCtx;

canvasCache.setAttribute('width', 400);
canvasCache.setAttribute('height', 400);

cacheCtx = canvasCache.getContext('2d');
cacheCtx.drawImage(someImage, 0, 0);

// later...
mainCtx.drawImage(canvasCache, 0, 0);
Double Buffering
Basic Idea
• drawImage() (to screen) is expensive
• Build a whole screen cache in a back buffer
  (in memory)
• Draw entities to that cache with
  drawImage() during render
• Write the entire cache to the screen with a
  single drawImage() call
Basic Idea
• drawImage() (to screen) is expensive
• Build a whole screen cache in a back buffer
  (in memory)
• Draw entities to that cache with
  drawImage() during render
• Write the entire cache to the screen with a
  single drawImage() call
var backBuffer = document.createElement('canvas'),
    backBufferCtx;
backBufferCtx = canvasCache.getContext('2d');

// later...
var render = function () {
    var i, ent;
    mainCtx.drawImage(backBuffer, 0, 0);

    for (i = 0; i > entities.length; i++) {
        ent = entities[i];
        // this is not quite what you'd do but...
        backBufferCtx.drawImage(ent.cache, ent.x, ent.y)
    }
}
Layered Images
Similar thing...
• Save drawImage() calls by compositing into a
  cache
• Draw multiple images to the same cache in
  order
• Attach the cache to a single game entity
• Write the composited cache to your frame
  buffer in your draw call.
=
+
...and much more!
3) 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
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!
Image Filters
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;
    }
Also possible, (but
 not necessarily
  recommended)
• Masking (if the pixel is colored in one
  image...)
• Pixel-wise composition.
• Etc.!
Caveats

• Cross-domain issues: if your data came from
  somewhere untrusted, the browser will not
  send it to the GPU.
• Canvas calls exist for some of these things.
• You can easily produce garbage.
Questions?
Thanks!



Slides: http://j.mp/stupidcanvastricks

dean@massivelyfun.com, @deanero
   http://massivelyfun.com/jobs

Weitere ähnliche Inhalte

Was ist angesagt?

ARTDM 170, Week13: Processing
ARTDM 170, Week13: ProcessingARTDM 170, Week13: Processing
ARTDM 170, Week13: Processing
Gilbert Guerrero
 
Th 0230 turbo_chargeyourui-howtomakeyourandroidu_ifastandefficient
Th 0230 turbo_chargeyourui-howtomakeyourandroidu_ifastandefficientTh 0230 turbo_chargeyourui-howtomakeyourandroidu_ifastandefficient
Th 0230 turbo_chargeyourui-howtomakeyourandroidu_ifastandefficient
Bin Shao
 

Was ist angesagt? (20)

Drawing with the HTML5 Canvas
Drawing with the HTML5 CanvasDrawing with the HTML5 Canvas
Drawing with the HTML5 Canvas
 
HTML 5_Canvas
HTML 5_CanvasHTML 5_Canvas
HTML 5_Canvas
 
HTML5 Canvas - The Future of Graphics on the Web
HTML5 Canvas - The Future of Graphics on the WebHTML5 Canvas - The Future of Graphics on the Web
HTML5 Canvas - The Future of Graphics on the Web
 
Building a Visualization Language
Building a Visualization LanguageBuilding a Visualization Language
Building a Visualization Language
 
HTML 5 Canvas & SVG
HTML 5 Canvas & SVGHTML 5 Canvas & SVG
HTML 5 Canvas & SVG
 
Efek daun
Efek daunEfek daun
Efek daun
 
How to make a video game
How to make a video gameHow to make a video game
How to make a video game
 
Canvas - HTML 5
Canvas - HTML 5Canvas - HTML 5
Canvas - HTML 5
 
Wallpaper Notifier
Wallpaper NotifierWallpaper Notifier
Wallpaper Notifier
 
UIWebViewでつくるUI
UIWebViewでつくるUIUIWebViewでつくるUI
UIWebViewでつくるUI
 
WebGL and three.js - Web 3D Graphics
WebGL and three.js - Web 3D Graphics WebGL and three.js - Web 3D Graphics
WebGL and three.js - Web 3D Graphics
 
ARTDM 170, Week13: Processing
ARTDM 170, Week13: ProcessingARTDM 170, Week13: Processing
ARTDM 170, Week13: Processing
 
Th 0230 turbo_chargeyourui-howtomakeyourandroidu_ifastandefficient
Th 0230 turbo_chargeyourui-howtomakeyourandroidu_ifastandefficientTh 0230 turbo_chargeyourui-howtomakeyourandroidu_ifastandefficient
Th 0230 turbo_chargeyourui-howtomakeyourandroidu_ifastandefficient
 
Having fun with graphs, a short introduction to D3.js
Having fun with graphs, a short introduction to D3.jsHaving fun with graphs, a short introduction to D3.js
Having fun with graphs, a short introduction to D3.js
 
Variables
VariablesVariables
Variables
 
Game dev 101 part 2
Game dev 101   part 2Game dev 101   part 2
Game dev 101 part 2
 
Game dev 101 part 3
Game dev 101 part 3Game dev 101 part 3
Game dev 101 part 3
 
Maperitive
MaperitiveMaperitive
Maperitive
 
The Web map stack on Django
The Web map stack on DjangoThe Web map stack on Django
The Web map stack on Django
 
3D everywhere
3D everywhere3D everywhere
3D everywhere
 

Andere mochten auch

5 kinesis lightning
5 kinesis lightning5 kinesis lightning
5 kinesis lightning
BigDataCamp
 
Email &amp; Social Media Training
Email &amp; Social Media TrainingEmail &amp; Social Media Training
Email &amp; Social Media Training
William Mann
 

Andere mochten auch (20)

Webinar seo 2012
Webinar seo 2012Webinar seo 2012
Webinar seo 2012
 
quick sort by student of NUML university
quick sort by student of NUML universityquick sort by student of NUML university
quick sort by student of NUML university
 
Building Creative Product Extensions with Experience Manager
Building Creative Product Extensions with Experience ManagerBuilding Creative Product Extensions with Experience Manager
Building Creative Product Extensions with Experience Manager
 
Being polite to strangers
Being polite to strangersBeing polite to strangers
Being polite to strangers
 
ルイ·ヴィトンの荷物を購入
ルイ·ヴィトンの荷物を購入ルイ·ヴィトンの荷物を購入
ルイ·ヴィトンの荷物を購入
 
Universal Image Loader: Story, Architecture, FAQ
Universal Image Loader: Story, Architecture, FAQUniversal Image Loader: Story, Architecture, FAQ
Universal Image Loader: Story, Architecture, FAQ
 
Khaak aur khoon (dirt and blood) by naseem hijazi part 1
Khaak aur khoon (dirt and blood) by naseem hijazi part 1Khaak aur khoon (dirt and blood) by naseem hijazi part 1
Khaak aur khoon (dirt and blood) by naseem hijazi part 1
 
02 july-2014 to-08-july-2014-hindu_sabhavarta_year38_issue14
02 july-2014 to-08-july-2014-hindu_sabhavarta_year38_issue1402 july-2014 to-08-july-2014-hindu_sabhavarta_year38_issue14
02 july-2014 to-08-july-2014-hindu_sabhavarta_year38_issue14
 
365 产品介绍 产品推广app_20150721
365 产品介绍 产品推广app_20150721365 产品介绍 产品推广app_20150721
365 产品介绍 产品推广app_20150721
 
Top 10 Tips from Millionaires
Top 10 Tips from MillionairesTop 10 Tips from Millionaires
Top 10 Tips from Millionaires
 
Spine X Live2D 百萬智多星製作經驗談
Spine X Live2D 百萬智多星製作經驗談Spine X Live2D 百萬智多星製作經驗談
Spine X Live2D 百萬智多星製作經驗談
 
Kewirausahaan
KewirausahaanKewirausahaan
Kewirausahaan
 
Time Management within IT Project Management
Time Management within IT Project ManagementTime Management within IT Project Management
Time Management within IT Project Management
 
5 kinesis lightning
5 kinesis lightning5 kinesis lightning
5 kinesis lightning
 
Email &amp; Social Media Training
Email &amp; Social Media TrainingEmail &amp; Social Media Training
Email &amp; Social Media Training
 
Lobel LED Leaflet - New launching of LED Products in this Diwali.
Lobel LED Leaflet - New launching of LED Products in this Diwali.  Lobel LED Leaflet - New launching of LED Products in this Diwali.
Lobel LED Leaflet - New launching of LED Products in this Diwali.
 
Coastal carbon_Andy Steven
Coastal carbon_Andy StevenCoastal carbon_Andy Steven
Coastal carbon_Andy Steven
 
Team 1 c IMT oral presentation
Team 1 c IMT oral presentationTeam 1 c IMT oral presentation
Team 1 c IMT oral presentation
 
The Invention of Capitalism - Michael Perelman
The Invention of Capitalism - Michael PerelmanThe Invention of Capitalism - Michael Perelman
The Invention of Capitalism - Michael Perelman
 
Nce2文本
Nce2文本Nce2文本
Nce2文本
 

Ähnlich wie Stupid Canvas Tricks

Pointer Events in Canvas
Pointer Events in CanvasPointer Events in Canvas
Pointer Events in Canvas
deanhudson
 
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-phpapp02
PL dream
 
Canvas in html5 - TungVD
Canvas in html5 - TungVDCanvas in html5 - TungVD
Canvas in html5 - TungVD
Framgia Vietnam
 
Graphicsand animations devoxx2010 (1)
Graphicsand animations devoxx2010 (1)Graphicsand animations devoxx2010 (1)
Graphicsand animations devoxx2010 (1)
Marakana Inc.
 

Ähnlich wie Stupid Canvas Tricks (20)

Pointer Events in Canvas
Pointer Events in CanvasPointer Events in Canvas
Pointer Events in Canvas
 
HTML5 Animation in Mobile Web Games
HTML5 Animation in Mobile Web GamesHTML5 Animation in Mobile Web Games
HTML5 Animation in Mobile Web Games
 
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
 
Real life XNA
Real life XNAReal life XNA
Real life XNA
 
Intro to HTML5
Intro to HTML5Intro to HTML5
Intro to HTML5
 
Improving Game Performance in the Browser
Improving Game Performance in the BrowserImproving Game Performance in the Browser
Improving Game Performance in the Browser
 
Bitmap management like a boss
Bitmap management like a bossBitmap management like a boss
Bitmap management like a boss
 
Google I/O 2013 - Android Graphics Performance
Google I/O 2013 - Android Graphics PerformanceGoogle I/O 2013 - Android Graphics Performance
Google I/O 2013 - Android Graphics Performance
 
Google I/O 2013 - Android Graphics Performance
Google I/O 2013 - Android Graphics PerformanceGoogle I/O 2013 - Android Graphics Performance
Google I/O 2013 - Android Graphics Performance
 
HTML5 - Chances and Pitfalls (Bytro Labs GmbH)
HTML5 - Chances and Pitfalls (Bytro Labs GmbH)HTML5 - Chances and Pitfalls (Bytro Labs GmbH)
HTML5 - Chances and Pitfalls (Bytro Labs GmbH)
 
Massimo Artizzu - The tricks of Houdini: a magic wand for the future of CSS -...
Massimo Artizzu - The tricks of Houdini: a magic wand for the future of CSS -...Massimo Artizzu - The tricks of Houdini: a magic wand for the future of CSS -...
Massimo Artizzu - The tricks of Houdini: a magic wand for the future of CSS -...
 
Canvas in html5 - TungVD
Canvas in html5 - TungVDCanvas in html5 - TungVD
Canvas in html5 - TungVD
 
Learning Predictive Modeling with TSA and Kaggle
Learning Predictive Modeling with TSA and KaggleLearning Predictive Modeling with TSA and Kaggle
Learning Predictive Modeling with TSA and Kaggle
 
DIY Java Profiling
DIY Java ProfilingDIY Java Profiling
DIY Java Profiling
 
From Zero to Hero – Web Performance
From Zero to Hero – Web PerformanceFrom Zero to Hero – Web Performance
From Zero to Hero – Web Performance
 
Browsers with Wings
Browsers with WingsBrowsers with Wings
Browsers with Wings
 
Amir Salihefendic: Redis - the hacker's database
Amir Salihefendic: Redis - the hacker's databaseAmir Salihefendic: Redis - the hacker's database
Amir Salihefendic: Redis - the hacker's database
 
Graphicsand animations devoxx2010 (1)
Graphicsand animations devoxx2010 (1)Graphicsand animations devoxx2010 (1)
Graphicsand animations devoxx2010 (1)
 
Machine Learning for Web Developers
Machine Learning for Web DevelopersMachine Learning for Web Developers
Machine Learning for Web Developers
 

Kürzlich hochgeladen

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
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
giselly40
 

Kürzlich hochgeladen (20)

Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
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
 
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
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 

Stupid Canvas Tricks

  • 1. Stupid Canvas Tricks
  • 2. Who Am I? Dean Hudson, @deanero Bit Twiddler at Massively Fun
  • 3. We make games with open web technology. We’re hiring!
  • 4. What this is? • Tips tricks and about the Canvas API • 2D Context • Focus on game programming • Focus on bitmaps • Me v. Me Lightning Talks
  • 5. What this isn’t • A talk about WebGL • Terribly deep on any one topic • A JavaScript or Canvas API tutorial
  • 6. But first: the dumbest trick I could think of
  • 7.
  • 8. Pro Tip: Use HSL instead of RGB when interpolating color.
  • 11. Outline • Call requestAnimationFrame • Handle queued UI events • Call update on your game entities • Render!
  • 12. Outline • Call requestAnimationFrame • Handle queued UI events • Call update on your game entities • Render!
  • 13. // game loop gameLoop = { run: function () { this.id = requestAnimationFrame(this.run); update(); draw(); }, stop: function () { cancelAnimationFrame(this.id); } }; gameLoop.run();
  • 14. RAF Shim • Lots of examples on the internet • Set RAF to whichever your browser has • Fallback to set timeout at ~16ms
  • 15. 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); }; }
  • 17. chrome://tracing • Wrap things you care about in console.time() / console.timeEnd() calls • Bring up tracing in a tab • Downside: console spam
  • 18. var profile = function (name, cb) { console.time(name); cb(); console.timeEnd(name); } // then later... profile('render', function () { // my render call. render(); });
  • 19.
  • 21. Testing Canvas is hard. • PhantomJS (A little scary...) • Stub out the Canvas API
  • 22. Testing Canvas is hard. • PhantomJS (A little scary...) • Stub out the Canvas API
  • 24. Basic Technique • Create a canvas element in your code • Get its context • Write pixels to that context • Use the canvas in a drawImage() call on another canvas context • YOU DON’T ADD THE CACHED CANVAS TO THE DOM!
  • 25. var canvasCache = document.createElement('canvas'), cacheCtx; canvasCache.setAttribute('width', 400); canvasCache.setAttribute('height', 400); cacheCtx = canvasCache.getContext('2d'); cacheCtx.drawImage(someImage, 0, 0); // later... mainCtx.drawImage(canvasCache, 0, 0);
  • 27. Basic Idea • drawImage() (to screen) is expensive • Build a whole screen cache in a back buffer (in memory) • Draw entities to that cache with drawImage() during render • Write the entire cache to the screen with a single drawImage() call
  • 28. Basic Idea • drawImage() (to screen) is expensive • Build a whole screen cache in a back buffer (in memory) • Draw entities to that cache with drawImage() during render • Write the entire cache to the screen with a single drawImage() call
  • 29. var backBuffer = document.createElement('canvas'), backBufferCtx; backBufferCtx = canvasCache.getContext('2d'); // later... var render = function () { var i, ent; mainCtx.drawImage(backBuffer, 0, 0); for (i = 0; i > entities.length; i++) { ent = entities[i]; // this is not quite what you'd do but... backBufferCtx.drawImage(ent.cache, ent.x, ent.y) } }
  • 31. Similar thing... • Save drawImage() calls by compositing into a cache • Draw multiple images to the same cache in order • Attach the cache to a single game entity • Write the composited cache to your frame buffer in your draw call.
  • 32. = +
  • 34. 3) Your Friend, ImageData
  • 35. 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
  • 36. Single pixel Array offsets 0 1 2 3 R G B A 8 bits 8 bits 8 bits 8 bits 4 bytes
  • 39. 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.
  • 40. 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; }
  • 41. DON’T FORGET: each idata.data value is between 0-255!
  • 43. 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!
  • 44. 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; } };
  • 45. 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; }
  • 46. Also possible, (but not necessarily recommended) • Masking (if the pixel is colored in one image...) • Pixel-wise composition. • Etc.!
  • 47. Caveats • Cross-domain issues: if your data came from somewhere untrusted, the browser will not send it to the GPU. • Canvas calls exist for some of these things. • You can easily produce garbage.

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
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n
  43. \n
  44. \n
  45. \n
  46. \n
  47. \n
  48. \n
  49. \n