Created
July 4, 2023 07:00
-
-
Save Demandrel/f653f629cf342497d3601e804584f4bd to your computer and use it in GitHub Desktop.
GeneratingGif
This file contains 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
//here load libraries (html2gif and gif.js) | |
async startRecording() { //record the gif and export it | |
const hiddenCanvas = document.getElementById('hiddenCanvas'); | |
const ctx = hiddenCanvas.getContext('2d'); | |
const yourDiv = document.getElementById('capture'); | |
hiddenCanvas.width = 480 | |
hiddenCanvas.height = 480 | |
const stream = hiddenCanvas.captureStream(30); // 30 FPS | |
this.recorder = RecordRTC(stream, { type: 'video' }); | |
this.recorder.startRecording(); | |
const drawCanvas = async () => { | |
if (this.isRecording) { | |
html2canvas(yourDiv).then((canvas) => { | |
ctx.drawImage(canvas, 0, 0, hiddenCanvas.width, hiddenCanvas.height); | |
this.animationFrameId = requestAnimationFrame(drawCanvas); | |
}); | |
} | |
}; | |
this.isRecording = true; | |
drawCanvas(); | |
setTimeout(this.stopRecording, this.recordTime); | |
}, | |
async stopRecording() { | |
cancelAnimationFrame(this.animationFrameId); | |
this.isRecording = false; | |
this.recorder.stopRecording(async () => { | |
const blob = await this.recorder.getBlob(); | |
// Convert the blob to a object URL | |
const url = URL.createObjectURL(blob); | |
gifshot.createGIF({ | |
video: [url], | |
gifWidth: 480, | |
gifHeight: 480, | |
}, function(obj) { | |
if(!obj.error) { | |
const image = obj.image; | |
const animatedImage = document.createElement('img'); | |
animatedImage.src = image; | |
const anchor = document.createElement('a'); | |
anchor.href = image; | |
anchor.download = 'recording.gif'; | |
anchor.click(); | |
} | |
}); | |
}); | |
}, | |
takeGifScreenShot() { //just takes a screenshot to test html2canvas | |
html2canvas(document.querySelector("#capture")).then(canvas => { | |
let link = document.createElement('a') | |
link.href = canvas.toDataURL("image/png") | |
link.download = 'screenshot.png' | |
link.click() | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment