Created
October 3, 2018 23:55
-
-
Save andrejpavlovic/b857e73887104ccc0bb71988573025b0 to your computer and use it in GitHub Desktop.
Sample conversion of gifuct-js frames to <img> elements.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function renderImagesFromFrames(frames, width, height) { | |
// gif patch canvas | |
const tempCanvas = document.createElement('canvas'); | |
const tempCtx = tempCanvas.getContext('2d'); | |
// full gif canvas | |
const gifCanvas = document.createElement('canvas'); | |
gifCanvas.width = width || frames[0].dims.width; | |
gifCanvas.height = height || frames[0].dims.height; | |
const gifCtx = gifCanvas.getContext('2d'); | |
// render images from frame patches | |
let frameImageData; | |
return frames.map(function(frame) { | |
const dims = frame.dims; | |
if(!frameImageData || dims.width != frameImageData.width || dims.height != frameImageData.height){ | |
tempCanvas.width = dims.width; | |
tempCanvas.height = dims.height; | |
frameImageData = tempCtx.createImageData(dims.width, dims.height); | |
} | |
// set the patch data as an override | |
frameImageData.data.set(frame.patch); | |
// draw the patch back over the canvas | |
tempCtx.putImageData(frameImageData, 0, 0); | |
// store previous image data | |
const previousFrameImageData = gifCtx.getImageData(0, 0, gifCanvas.width, gifCanvas.height); | |
// draw patch on full gif canvas | |
gifCtx.drawImage(tempCanvas, dims.left, dims.top); | |
// create image | |
const tmpImg = fabric.util.createImage(); | |
tmpImg.src = gifCanvas.toDataURL('image/png'); | |
tmpImg.width = gifCanvas.width; | |
tmpImg.height = gifCanvas.height; | |
// Indicates the way in which the graphic is to | |
// be treated after being displayed. | |
switch(frame.disposalType) { | |
case 0: | |
// No disposal specified. The decoder is | |
// not required to take any action. | |
break; | |
case 1: | |
// Do not dispose. The graphic is to be left | |
// in place. | |
break; | |
case 2: | |
// Restore to background color. The area used by the | |
// graphic must be restored to the background color. | |
gifCtx.clearRect(dims.left, dims.top, dims.width, dims.height); | |
break; | |
case 3: | |
// Restore to previous. The decoder is required to | |
// restore the area overwritten by the graphic with | |
// what was there prior to rendering the graphic. | |
gifCtx.clearRect(0, 0, gifCanvas.width, gifCanvas.height); | |
gifCtx.putImageData(previousFrameImageData, 0, 0); | |
break; | |
default: | |
// Reserved for future use | |
break; | |
} | |
return tmpImg; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment