How do I do an "onload" on NODE.JS? (Discord.js)

2

I've been trying to make a code to generate an image on node.js using Canvas , but I'm facing the problem that the image is not loaded before using it. I tried using "onload" but that did not work (I never ran the code)

Here is the "base" of my code

const Canvas = require('canvas-prebuilt'), Image = Canvas.Image;


var canvas = new Canvas(300, 300);
var ctx = canvas.getContext('2d');
var img1 = new Image();

ctx.drawImage(img1, 100, 90, canvas.height / 6, canvas.height / 6);
    
asked by anonymous 05.06.2017 / 20:42

1 answer

0

Try to use node-canvas .

Here's the sample code , see documentation . With some adaptations using http to create the http server and display the image:

var http = require('http'), fs = require('fs'), 
Canvas = require('canvas');
var port = 3000;

http.createServer(function (req, res) {
    fs.readFile(__dirname + '/image.jpg', function(err, data) {
        if (err) throw err;
        var img = new Canvas.Image; // Create a new Image
        img.src = data;

        // Inicialize uma nova tela com as mesmas dimensões
        // e use um contexto de desenho 2D para isso.
        var canvas = new Canvas(img.width, img.height);
        var ctx = canvas.getContext('2d');
        ctx.drawImage(img, 0, 0, img.width / 4, img.height / 4);

        //crie os htmls para mostrar a img
        res.write('<html><body>');
        res.write('<img src="' + canvas.toDataURL() + '" />');
        res.write('</body></html>');
        res.end();
    });

}).listen(port, "localhost");
console.log('Acesse localhost ' + port);
    
06.06.2017 / 14:40