imagenode.jscanvashtml5-canvas

nodejs - How to add image data from file into canvas


The following code is supposed to read an image file and then add the file data into a canvas with the help of the Canvas module.

When I run this code I receive the error message Image is not defined. Is the image object that I'm trying to initialise from a module that I simply import?

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

http.createServer(function (req, res) {
    fs.readFile(__dirname + '/image.jpg', function(err, data) {
        if (err) throw err;
        img = new Image();
        img.src = data;
        ctx.drawImage(img, 0, 0, img.width / 4, img.height / 4);

        res.write('<html><body>');
        res.write('<img src="' + canvas.toDataURL() + '" />');
        res.write('</body></html>');
        res.end();
    });

}).listen(8124, "127.0.0.1");
console.log('Server running at http://127.0.0.1:8124/');

Solution

  • I apologize if I'm wrong here, but it looks like you've found this code somewhere and tried to use it without actually understanding what's happening under the covers. Even if you were to fix the Image is not defined error, there are many others.

    I have the fixed code at the end of this post, but I'd recommend thinking more deeply about these issues in the code from your question:

    I'd recommend reading documentation more closely and looking more closely at any example code you copy into your own applications in the future.


    Here is the fixed code, with some comments to explain my changes. I figured this out by taking a quick look at the documentation at https://github.com/learnboost/node-canvas.

    var http = require('http'), fs = require('fs'), 
    Canvas = require('canvas');
    
    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;
    
            // Initialiaze a new Canvas with the same dimensions
            // as the image, and get a 2D drawing context for it.
            var canvas = new Canvas(img.width, img.height);
            var ctx = canvas.getContext('2d');
            ctx.drawImage(img, 0, 0, img.width / 4, img.height / 4);
    
            res.write('<html><body>');
            res.write('<img src="' + canvas.toDataURL() + '" />');
            res.write('</body></html>');
            res.end();
        });
    
    }).listen(8124, "127.0.0.1");
    console.log('Server running at http://127.0.0.1:8124/');