Gif animated in canvas
Posted: Mon Jan 05, 2026 4:24 pm
Hi! Now that I'm recovered from the hangover
. After a long period without sharing code, I return to the attack!
I want to share this code to use animated gifs in a canvas.
Was teste with many gifs and all work here. Tell me if not work for you, and please shar if you impreve the code.
The system use timer taked from the gif, but if is not defined '0', then use this var defaultDelay=60 ms.
I hope be interesting for you.
Note: Can work in sprites, images and textures if you change the output. Can use transparent images if you use DrawAlphaImage.
I want to share this code to use animated gifs in a canvas.
Was teste with many gifs and all work here. Tell me if not work for you, and please shar if you impreve the code.
The system use timer taked from the gif, but if is not defined '0', then use this var defaultDelay=60 ms.
I hope be interesting for you.
Note: Can work in sprites, images and textures if you change the output. Can use transparent images if you use DrawAlphaImage.
Code: Select all
UseGIFImageDecoder()
Structure gif_data: img.i:frames.i:frame.i:width.i:height.i:timer.i:output.i: List spd.f():EndStructure: Global gif.gif_data
Procedure gifLoad(canvas, file.s="mygif.gif", defaultDelay=60)
If FileSize(file)>0
If IsImage(gif\img):FreeImage(gif\img):EndIf: ClearList(gif\spd())
gif\img= LoadImage(#PB_Any,file,0)
gif\width= ImageWidth(gif\img): gif\height= ImageHeight(gif\img): gif\frames= ImageFrameCount(gif\img): gif\output= canvas
For p= 0 To gif\frames-1
SetImageFrame(gif\img,p): AddElement(gif\spd())
gif\spd()= GetImageFrameDelay(gif\img): If gif\spd()= 0: gif\spd()= defaultDelay: EndIf
Next p
ProcedureReturn #True
Else
ProcedureReturn #False
EndIf
EndProcedure
Procedure gifPlayer()
If gif\img
If ElapsedMilliseconds() > gif\timer
SetImageFrame(gif\img, gif\frame)
StartDrawing(CanvasOutput(gif\output)): DrawImage(ImageID(gif\img),0,0): StopDrawing()
gif\frame +1: If gif\frame >= gif\frames: gif\frame= 0: EndIf
gif\timer= ElapsedMilliseconds() + gif\spd()
EndIf
EndIf
EndProcedure
OpenWindow(0,0,0,500,281,"Gif animated v1.0",#PB_Window_SystemMenu | #PB_Window_ScreenCentered)
canvas= CanvasGadget(#PB_Any,0,0,WindowWidth(0),WindowHeight(0))
ok= gifLoad(canvas, "D:\_MIO\OS Multi\GIF\giphy.gif"): Debug "File loaded= "+ ok
Repeat
ev= WindowEvent()
Select ev
Case #PB_Event_Gadget
eg=EventGadget():et=EventType()
Select eg
Case 0
EndSelect
Case #PB_Event_CloseWindow
Break
EndSelect
gifPlayer(): Delay(1)
ForEver
