Jakho

Jakho

Full Stack developer.
x

Solution for installing node-canvas on M1/M2 Mac

Recently, I had a requirement to generate a batch of text images. As a front-end developer, my first thought was to use canvas to draw and save them as base64 images.

However, if I want to generate them in bulk using browser DOM, it will be relatively cumbersome to save them. This requires using Node to handle the process. In Node, in order to call the canvas environment, we must install the node-canvas module dependency. However, when I tried to install node-canvas on my M2 Mac device, I encountered an error. It prompted:

Attempting to get 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 (same as yours). Unfortunately, there is no sign of this version on the release page https://github.com/Automattic/node-canvas/releases.

In other words, the official node-canvas does not actually provide a source for node-canvas related to arm64, so we need to find another solution.

If you want to install node-canvas, node-gyp is definitely essential. First, we need to install node-gyp (skip this step if you have already installed it) to avoid long waiting times or errors when installing dependencies later.

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 Mac.

Enter the following command in the terminal window:

npm install -g node-gyp

This command globally installs the node-gyp package. Wait for the installation to complete.

Install node-canvas#

First, you need to install the homebrew tool. Please accurately copy and paste these commands 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 is completed, it will tell you to export several paths to complete the installation. Execute these operations, otherwise it will not work.

node-canvas-install

After completing the above steps, re-enter npm install node-canvas. If everything goes well, the installation should be successful. According to the repository's issue, it seems that using node-canvas in a Linux environment is more troublesome, especially with higher versions of Node. You may need to use a specific version, otherwise it will not be installed successfully.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.