Created
March 7, 2015 23:13
-
-
Save piuggi/7b2eb44b623985ca4445 to your computer and use it in GitHub Desktop.
Looping Text Gif with Node.js using node-canvas gifencoder
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
var Canvas = require('canvas'), | |
GIFEncoder = require('gifencoder'), | |
fs = require('fs'), | |
path = require('path'); | |
var width = 500, height = 500; | |
var encoder = new GIFEncoder(width, height); | |
encoder.createReadStream().pipe(fs.createWriteStream('myanimated.gif')); | |
encoder.start(); | |
encoder.setRepeat(0); | |
encoder.setDelay(0); | |
encoder.setQuality(10); | |
var canvas = new Canvas(width, height); | |
var ctx = canvas.getContext('2d'); | |
var bDraw = true; | |
var drawCount = 0; | |
var userName = "Joe Joey"; | |
var textToDraw = 'Hey, I\'m Joe'; | |
var x=width, y; | |
function drawText(){ | |
ctx.font = "30px Verdana"; | |
x-=2; | |
var tWidth = 0-ctx.measureText(textToDraw).width; | |
console.log("x: "+x+" tWidth: "+ tWidth) | |
console.log(x < tWidth) | |
if (x < tWidth) return endDraw(); //x = 10; | |
ctx.font = "10px Verdana"; | |
ctx.fillStyle = "#000000"; | |
ctx.fillText(userName,x, 50); | |
// Create gradient | |
// var gradient=ctx.createLinearGradient(0,0,width,0); | |
// gradient.addColorStop(0,"magenta"); | |
// gradient.addColorStop(0.5,"blue"); | |
// gradient.addColorStop(1.0,"red"); | |
// Fill with gradient | |
ctx.font = "30px Verdana"; | |
ctx.fillStyle='#FFFFFF'; | |
ctx.fillText(textToDraw,x,80); | |
if(x < 0){ | |
ctx.font = "10px Verdana"; | |
ctx.fillStyle = "#000000"; | |
ctx.fillText(userName,width+x, 50); | |
ctx.font = "30px Verdana"; | |
ctx.fillStyle='#FFFFFF'; | |
ctx.fillText(textToDraw,width+x,80); | |
} | |
} | |
function drawGreen(){ | |
console.log(" Green") | |
// green rectangle | |
ctx.fillStyle = '#00ff00'; | |
ctx.fillRect(0, 0, width, height); | |
drawText(); | |
encoder.addFrame(ctx); | |
} | |
function drawBlue(){ | |
console.log(" Blue") | |
// blue rectangle | |
ctx.fillStyle = '#0000ff'; | |
ctx.fillRect(0, 0, width, height); | |
drawText(); | |
encoder.addFrame(ctx); | |
} | |
function drawRed(){ | |
console.log(" Red") | |
// red rectangle | |
ctx.fillStyle = '#ff0000'; | |
ctx.fillRect(0, 0, width, height); | |
drawText(); | |
encoder.addFrame(ctx); | |
} | |
function endDraw(){ | |
console.log('no more'); | |
bDraw = false; | |
encoder.finish(); | |
} | |
function draw(){ | |
drawCount++; | |
console.log('draw count: '+drawCount+'drawing...'); | |
//if(drawCount > 100) return endDraw(); | |
if(drawCount % 3 === 0) return drawRed(); | |
if(drawCount % 2 === 0) return drawBlue(); | |
return drawGreen(); | |
} | |
while(bDraw) draw(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment