I'm trying to make a Twitter bot that generates a random rgb colour, creates a picture of this colour and tweets it. I've created a piece of JS that can generate and tweet a random rgb value and a piece of javascript that can generate a picture of a random colour but I'm not sure how to combine the two.
My problem is that I can't generate the PNG image without having a document. If I run the script on a server using Node.JS there isn't a document to create the canvas in. Is there any other way to create a png picture (maybe by temporarily saving it to the server) and attaching it to a tweet?
Thanks for your help!
This is the code I have for tweeting a random value:
var Twit = require('twit')
var T = new Twit({
consumer_key: '###',
consumer_secret: '###',
access_token: '###',
access_token_secret: '###'
})
function tweet() {
//Generate a random colour
var r = Math.floor((Math.random() * 256));
var g = Math.floor((Math.random() * 256));
var b = Math.floor((Math.random() * 256));
var color = "rgb("+r+","+g+","+b+")";
// tweet that colour
T.post('statuses/update', { status: color });
}
setTimeout(tweet, 30000);
And this is a JS script that generates a PNG file of a random colour on a web page:
var r = Math.floor((Math.random() * 256));
var g = Math.floor((Math.random() * 256));
var b = Math.floor((Math.random() * 256));
var color = "rgb("+r+","+g+","+b+")";
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
// draw box
context.beginPath();
context.moveTo(0, 00);
context.lineTo(0, 800);
context.lineTo(800, 800);
context.lineTo(800, 0);
context.closePath();
context.lineWidth = 5;
context.fillStyle = color;
context.fill();
// save canvas image as data url (png format by default)
var dataURL = canvas.toDataURL();
// set canvasImg image src to dataURL
// so it can be saved as an image
document.getElementById('canvasImg').src = dataURL;
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…