1

I'm currently transfering a base64 image from a client to my server with socket.io. On the server, I want to render that base64 image into my canvas.

The code is:

function newSlide(slideImage){
  socket.broadcast.emit('newSlide', slideImage);
  var img = new Image;
  img.src = slideImage;
  ctx.drawImage(img, 0, 0);
}

With that code, on the client everything is working, I can load the base64 image into a normal canvas, but on my server in server.js (where this code is), it's not working, I'm getting an error saying Image is not defined at the line new Image, when trying without the image-creation and just put in the base64 string, it says image or canvas excepted.

What's the problem with the image creation, why does it not work? And what can I do to make it working?

nameless
  • 1,483
  • 5
  • 32
  • 78
  • You can't display the image on the server, you need to display it on the client side.. you probably want to just send the image data over to the client, have the client receive and display it. – Liam MacDonald Jul 18 '17 at 09:15
  • @LiamMacDonald but I somehow need it on the server side... after it is in node-canvas it goes on, so I need it there – nameless Jul 18 '17 at 09:20

3 Answers3

2

Image is part of the DOM API and so is not present in the Node runtime.

To do what you want you're going to have to import a module that allows you to emulate some of the DOM APIs.

Aron
  • 8,696
  • 6
  • 33
  • 59
  • I've never needed to use one myself but [jsdom](https://github.com/tmpvar/jsdom) might be able to help – Aron Jul 18 '17 at 09:28
  • looks not that easy...I'm wondering if there is a way to maybe create a canvas with directly that base64 without converting it to an image? – nameless Jul 18 '17 at 09:33
0

It should be new Image(), not new Image

Qiao Wen
  • 21
  • 3
0

node-canvas provides loadImage which accepts base64 and appears to be a promisified Image() at a quick glance (although it provides Image as well, which seems to work fine just like the browser):

const {createCanvas, loadImage} = require("canvas"); // ^2.11.0
const fs = require("node:fs/promises");

(async () => {
  // sample (very small) base64 image
  const b64 = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAIAQMAAAD+wSzIAAAABlBMVEX///+/v7+jQ3Y5AAAADklEQVQI12P4AIX8EAgALgAD/aNpbtEAAAAASUVORK5CYII";
  const img = await loadImage(b64);
  const canvas = createCanvas(img.width, img.height);
  canvas.getContext("2d").drawImage(img, 0, 0);

  // just to show it worked, convert back to base64 and write to file
  await fs.writeFile("test.png", canvas.toDataURL().split(",")[1], "base64");
})();
ggorlen
  • 44,755
  • 7
  • 76
  • 106