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

Asked

Viewed 193 times

2

I’ve been trying to make a code for generate an image in Node.js using Canvas, but I am facing the problem that the image is not loaded before using it. I tried to use "onload" but it didn’t work (it never ran the code)


Here is the "basis" 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);

1 answer

1


Try to use the node-canvas.

Here is the code example, see the documentation. With some adaptations using http to create http server and show 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);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.