Skip to content

Use in Pure Node Js Script #93

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wordjelly opened this issue Aug 2, 2023 · 0 comments
Open

Use in Pure Node Js Script #93

wordjelly opened this issue Aug 2, 2023 · 0 comments

Comments

@wordjelly
Copy link

Hi,
I wanted to use this in a pure node js script, without involving a browser in any way.
I tried the following :

const { createCanvas, loadImage } = require('canvas');
const Granim = require('granim');

function generateGradient(title, subtitle, callback) {
  const canvasWidth = 400;
  const canvasHeight = 400;

  const canvas = createCanvas(canvasWidth, canvasHeight);
  console.log(canvas);
  const ctx = canvas.getContext('2d');
  console.log(ctx);
  
  const granimInstance = new Granim({
    element: canvas,
    name: 'basic-gradient',
    direction: 'left-right',
    opacity: [1, 1],
    isPausedWhenNotInView: true,
    states: {
      "default-state": {
        gradients: [
          ['#834D9B', '#D04ED6'],
          ['#1CD8D2', '#93EDC7'],
          ['#FD4688', '#B41D52']
        ],
        transitionSpeed: 7000
      }
    }
  });

  granimInstance.events.add('endGradient', () => {
    const fileName = `gradient_${Date.now()}.png`;
    const outputPath = path.join(__dirname, fileName);

    const out = require('fs').createWriteStream(outputPath);
    const stream = canvas.createPNGStream();
    stream.pipe(out);

    out.on('finish', () => {
      callback(null, fileName);
    });

    out.on('error', (err) => {
      callback(err, null);
    });
  });
}

module.exports = generateGradient;

generateGradient("dog","cat");

This fails as it seems that Granim is looking for the class HTMLCanvasElement to be defined in the global namespace

ReferenceError: HTMLCanvasElement is not defined
    at Granim.module.exports [as getElement] (/.../node_modules/granim/lib/getElement.js:4:25)

How do you get this to work? I tried refactoring that to not look for the HTMLCanvasElement, but there are references all over the codebase to things like "window" and other browser specific javascript functions/namespaces.

Is there any way to make this library work in a pure node js script?

Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant