Wiki
Clone wikiCore / ScreenCapture
Screen capture
Simple situations
If the code executed when the draw()
function is called does not use the setContext()
function, then you can make use of setContext()
to capture the screen, as illustrated in the code below:
function captureScreen()
local screenCap = image(WIDTH, HEIGHT) -- create an image the size of the screen
setContext(screenCap) -- set the context to the image
draw() -- draw a new frame (to the new context)
-- assumes draw will not alter the context
setContext() -- return the context to the screen
return screenCap -- return the image
end
(Credits: Simeon.)
More complex situations
If the code executed when the draw()
function is called itself calls setContext()
, then a more complex approach is required. See the example below.
-- Establish two global variables
_setContext = setContext -- one to preserve the built-in setContext() function
_screenContext = nil -- if not nil, one to act as buffer to replace the screen
-- Overwrite the built-in setContext() function, before it is ever called
setContext = function(img)
if img then return _setContext(img) end -- use img, if exists
if _screenContext then return _setContext(_screenContext) end -- use buffer, if exists
return _setContext() -- otherwise, call without arguments
end
function captureScreen()
_screenContext = image(WIDTH, HEIGHT) -- initialise buffer the size of the screen
draw() -- draw a new frame (to the buffer)
local screenCap = _screenContext -- preserve the buffer
_screenContext = nil -- set buffer to nil, restoring screen
return screenCap -- return the image
end
The effect of the code is to substitute setContext(_screenContext)
for setContext()
, if _screenContext
is not nil
. The captureScreen()
function takes care that _screenContext
has a suitable image assigned to it, before draw()
is called.
Updated