Recently, I had a requirement to batch generate a set of text images. As a front-end developer, the first thought was to use canvas to draw and save it as a base64 image.
However, for batch production, doing this through the browser DOM can be relatively cumbersome when saving, which requires using Node for processing. To call the canvas environment in Node, it is necessary to install the node-canvas module dependency. However, when I tried to install node-canvas on my M2 Mac device, it reported an error, indicating:
Attempting to fetch a non-existent binary file https://github.com/Automattic/node-canvas/releases/download/v2.9.1/canvas-v2.9.1-node-v93-darwin-unknown-arm64.tar.gz (matching yours). Unfortunately, there is no sign of that version on the release page https://github.com/Automattic/node-canvas/releases
This means that the official node-canvas does not actually provide a node-canvas source for arm64, so an alternative solution is needed.
To install node-canvas, node-gyp is also essential. First, we need to install node-gyp (if already installed, you can skip this) to avoid long waiting times or errors during subsequent dependency installations.
Install and Configure node-gyp#
Open a terminal window and enter the following command:
export CXXFLAGS="-stdlib=libc++"
This command sets the C++ standard library to libc++, which is necessary for node-gyp to work on M1 Macs.
In the terminal window, enter the following command:
npm install -g node-gyp
This command will globally install the node-gyp package; just wait for the installation to complete.
Install node-canvas#
First, you need to install the Homebrew tool. Please copy and paste these commands accurately into the terminal and execute them step by step:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
arch -arm64 brew install pkg-config cairo pango libpng jpeg giflib librsvg
After the second command completes, it will instruct you to export several paths to complete the setup, as shown below. Please perform these actions; otherwise, it will not work.
After completing this, re-enter npm install node-canvas
, and if all goes well, it should install successfully. Looking at the repository's issues, it seems that using node-canvas in a Linux environment is more troublesome, especially with higher versions of Node, as you may need to use a specific version; otherwise, installation may fail.