@basiliogerman I can’t go into too much depth about how I use the canvas textures yet since the project I am working on is still in development and therefore under wraps for now. I can tell you that I use canvas textures in multiple ways but here is the main one.
I create a new texture using graphics.newTexture( { type=“canvas”, width=width, height=height } ). I draw onto the canvas using various display objects. I use the texture to create a new ImageRect of the same width and height as the canvas, I apply a predefined filter (e.g. blur, bulge, contrast, etc.) to the ImageRect. I then draw this ImageRect onto yet another canvas texture! I then use this canvas texture to create any number of new ImageRect objects. The code looks something like what is below. Blurs and other filters can be expensive, especially if the object is moving. This approach allows me to apply the filter once to the first canvas and then replicate the pre-filtered second texture onto as many display objects as I want while only incurring the filter cost once.
Note that Android flushes textures on application suspend. This forces me to flush the canvas texture caches upon application resume. And since I am using nested canvases, I have to flush the inner most canvas first and then work my way outward. Also, I allow a small time lapse between canvas cache flushes to allow the system to catch up between texture flushes.
All of the code below was extracted from my actual code and is not runnable as-is. It’s just meant as a starting point for those who are interested. For example, production code should check if the OS is Android before bothering to add the system event handler shown below.
local tex1 = graphics\_newTexture( { type="canvas", width=width, height=height } ) tex1:draw( content1 ) tex1:invalidate() local rect = display.newImageRect(tex1.filename, tex1.baseDir, width, height) rect.fill.effect = "filter.blurGaussian" local tex2 = graphics.newTexture( { type="canvas", width=width, height=height } ) tex2:draw( rect) tex2:invalidate() for i = 1, 100 do local rect2 = display.newImageRect(tex2.filename, tex2.baseDir, width, height) end
local function onSystemEvent( event ) if (event.type=="applicationResume") then tex1:invalidate("cache") timer.performWithDelay(100, function() tex2:invalidate("cache") end) end end Runtime:addEventListener("system", onSystemEvent)