Git Product home page Git Product logo

granim.js's Introduction

Granim.js Build Status codecov gitter

Create fluid and interactive gradient animations with this small javascript library.

See the demo site.

Install

From NPM

  • Run npm install granim --save

From Bower

  • Run bower install granim

Static

How to use

<!-- Create a <canvas> element -->
<canvas id="granim-canvas"></canvas>

<!-- Call the script -->
<script src="granim.min.js"></script>

<!-- Create a Granim instance -->
<script>
var granimInstance = new Granim({
   element: '#granim-canvas',
   name: 'granim',
   opacity: [1, 1],
   states : {
       "default-state": {
           gradients: [
               ['#834D9B', '#D04ED6'],
               ['#1CD8D2', '#93EDC7']
           ]
       }
   }
});
</script>

granim.js's People

Contributors

dependabot[bot] avatar m-arcus avatar pranaygp avatar rhanb avatar sarcadass avatar suhaotian avatar yliohenki avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

granim.js's Issues

Using on repeated elements

Hello. Is it possible to use Granim on multiple repeated elements within a page? Currently it only works on the first element, unless I define multiple instances of the init script to target different selectors?

// init
var newInstance = new Granim({
    element: '.gradient-bg',
    defaultStateName: 'state-1,
    direction: 'left-right',
    opacity: [1,1,1,1],
    isPausedWhenNotInView: true,
        states : {
            "state-1": {
                gradients: [
                    ['#AA076B', '#61045F'],
                    ['#02AAB0', '#00CDAC']
	        ],
	        transitionSpeed: 2500
           }
    }
});

Can't run the local server for the docs - contributing

Hi,

I followed the contribution guideline, everything works fine except the local server for the docs.
I want to make a PR for a new feature proposal that could be useful for many users but can't implement the docs.

npm start

> [email protected] start /Users/rhanb/Documents/DevLove/OSS/JS/granim.js
> cd docs/ && node server.js

/Users/rhanb/Documents/DevLove/OSS/JS/granim.js/docs/server.js:34
server.connection({ port: httpPort });
       ^

TypeError: server.connection is not a function
    at Object.<anonymous> (/Users/rhanb/Documents/DevLove/OSS/JS/granim.js/docs/server.js:34:8)
    at Module._compile (module.js:653:30)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)
    at tryModuleLoad (module.js:506:12)
    at Function.Module._load (module.js:498:3)
    at Function.Module.runMain (module.js:694:10)
    at startup (bootstrap_node.js:204:16)
    at bootstrap_node.js:625:3

Best regards

Change defaultStateName based on page

Hello. The site I am developing has a range of different states based on the specific colour palette of that page.

I would like to know if it would be possible to change the defaultStateName based on the current page being viewed? For example, I am using the below code to check the page and then change the state, but I'd like to adjust this so that I can simply switch the default state when changing pages. How could I incorporate something like this into the Granim settings?

Thanks.

if ($("body").hasClass("page-life")) {
    console.log('this page is life!')
    menuInstance.changeState('life-state');
}

Data attributes

Hey,

I have one problem.
I can't add gradients via data attribute.

V1 - this works ok:

var my_gradient = [['#000000', '#111111'],['#444444', '#777777'],['#aaaaaa', '#ffffff']];
var granimInstance = new Granim({
	states : {
		"default-state": {
			gradients: my_gradient
		}
	}
});

V2 - Don't work

var my_gradient = el.getAttribute('data-gradients') || [['#000000', '#111111'],['#444444', '#777777'],['#aaaaaa', '#ffffff']];
var granimInstance = new Granim({
	states : {
		"default-state": {
			gradients: my_gradient
		}
	}
});
<div data-gradients="[['#000000', '#111111'],['#444444', '#777777'],['#aaaaaa', '#ffffff']]">
	<canvas></canvas>
</div>

Please help.

Text Input Option

Could you add a text option which will be rendered in the middle of that canvas? Also an option for font and font-familiy + color.

Angular integration

Hello.I fount this library today.I was wondering.Is it possible to integrate it in an angular 2+ project.
If yes then how?

Thank you for your time

Feature request: dynamically change gradients

Hi!

Wonderful library! Not sure if anyone will have time for this by I have a request:
It would be great if you can dynamically change the gradient colors. I know you can have premade states setup and switch between them, but you can't update a state and then switch to it.

Again, great work! :)

Just for to understand!

Hi,
Is it possible to offer newcomers like me a very basic explanation of how to use your code?
I would like to have the description of each complete passage, how and where to add the code.
es: Where to insert the unzipped folder? - How to retrieve .js and .css files? - What to write on the html page?
I'm sorry, I tried to enter the codes that appear in the Tabs, but there was no result.
Thank you!

Improving performance

Hi there.
Thank you for providing this library! It is very powerful and easy to use.

I am currently working on a website based live wallpaper and I am planning to use the gradient as a background.
My problem is that I cant have it take much of the performance, as I want to add 3D models with three.js on top of it.
The gradient canvas will take up the entire viewport size.
Unfortunately this stresses out the GPU a lot - even when there is no animation going on.

As I just need transitions between different gradient states at certain events and no permanent looped gradient animation, I wanted to ask if there is an option to safe performance when there is no transition running between gradients and it is just a solid gradient.

Code_2021-07-20_22-09-16

chrome_2021-07-20_22-13-29

Regarding the example file:
As you can see, even though it is just a solid gradient it goes heavily on the GPU when displaying the page in Chrome.
Is there a way to resolve this issue?

Thank you very much!

Fully dispose Granim to avoid memory leak in SPA

Every Granim instance is registering events on window. These are currently not cleaned up, ie when calling pause or clear. So after navigating a few pages, there are still references to old granim instances and canvas elements. Resize and scroll performance may also be affected.

It would be great to have a .dispose() method to clean up the granim instance completely.

Blending modes

This is not a issue but a feature request.

Is an implementation of blending modes for gradients coming up? It would be really nice to be able to toggle these in combination with images laying underneath.

Add commit message guidelines

We should definitely add guidelines on what commit message should look like to the CONTRIBUTING.md

This issue was inspired by commit messages on #12

Glitch on Safari when the Canvas is updated too often/quickly

Hi @sarcadass ,

This issue is not related to the new version (congrats by the way 🎉 ).

I encountered this issue when I was working on my personal website.
To give more context, I was trying to change the gradients using the customDirection property when the user is panning an element. Basically I was updating the gradient direction from a mouse event position. (You can try it out here: https://rhanb.me/)

It works great, except on Safari and after digging a bit into this issue I found out that you apply the function clearRect(0, 0, this.x1, this.y1) twice when the changeDirection is called and when the makeGradient is called.

By removing the one of makeGradient everything works fine:

var gradient = this.setDirection();
	var elToSetClassOnClass = document.querySelector(this.elToSetClassOn).classList;
	var i = 0;
	// this.context.clearRect(0, 0, this.x1, this.y1);

	if (this.image) {
		this.context.drawImage(
			this.imageNode,
			this.imagePosition.x,
			this.imagePosition.y,
			this.imagePosition.width,
			this.imagePosition.height
		);
	}
       ....

I'm not doing a PR because I wanted your feedback first; removing this line could break something?

How to add more background images like slides

First Thanks for this wonderful job. Really I like to start using this plugin.

I need like this function. could you please add this features, it would be awesome.

image: { source: ['./Content/img/bgImage1.png', './Content/img/bgImage2.png'], blendingMode: 'multiply' },
Thanks Team.

Add "direction" in degrees

Hello!

It would be awesome, if you could extend the "direction" option with something like 130deg.

Thank you! :)

Use in Pure Node Js Script

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.

How to use with webpack?

I've tried to use

const Granim = require('granim/dist/granim.js');

but have empty object
image

Thanks for assistance.

Something wrong in vue3

I have a project using vue3, and here is part of my code:

<script setup>
import Granim from 'granim';
const logoAnimation = new Granim({
  element:'.logoCanvas',
})
</script>

<template>
  <div class="list">
    <canvas class="logoCanvas"></canvas>
    </div>
  
  </div>
  
</template>

The browser throws an error with Uncaught (in promise) Error: .logoCanvas could not be found in the DOM, how to solve the problem. :(

setting in background?

currently when applying the html the Gradient effect sits over all other content ? how do i make this display in the background with the content infront

CPU Usage

Hi @sarcadass! The gradient-animator looks great, thank you for open sourcing this! Wondering if you see it using too much CPU as well when you use them?

Change state on scroll

How can I change the color state on page scroll? I'm using an animated gradient as the page background color. I need to change colors as the user scrolls down the page to each new section. Thank you.

Add CHANGELOG

as @sarcadass indicated on gitter, we should add a changelog and keep track of our future updates on the project.

This should be as easy as looking at the commit log on github, and typing down a CHANGELOG

bower.json

Hey, could you add a bower.json file. Im mostly using bower in my projects for dependencies.

Thank you! Great script.

Trigger initialization

Hello,

I would like to use the gradients in multiple "tiles". It works so far, I can initialize them individually (eg. onClick change state).

But most of the tiles are not visible at the beginning (display: none), so when I initialize them, the scripts says they're 0 height an width. Only if I resize the window it recreates them and the gradient is visible.

Is it possible to trigger it?

Thank you!

Apply granim.js as a <div> background rather than to a <canvas> element

Great work. This is a feature request rather than an issue.
What would be really useful is if you could apply the animated gradient as a background to a <div> rather than having to apply it to a <canvas> element - this way you could use -webkit-background-clip:text to produce text with an animated gradient fill, rather than having to photoshop a .png image with the transparent text cut out to layer over the gradient (as in the fourth example on your demo page)?

Add Test Cases

We should definitely add test cases and set up CI and code coverage for project scalability.

@sarcadass Would you like to set up testing with Selenium as you mentioned in the contributing file, while I set up Travis and Codecov?

ie9 error

Works fabulously everywhere except ie9. I'm getting an error saying "unable to get property 'remove' of undefined or null reference". This error breaks all my other javascript on the page. I read the comments on another browser issue about using a polyfill for older browsers.. How would I implement that and would it fix this error?

Thanks!

Add Color-Stop-Position

Hello,

is it possible to add the feature with adding a color stop position to each color?

default:
['#fff', '#000', '#f0f']
optional:
[{color: '#fff', pos: 0}, {color: '#000', pos: .3}, {color: '#f0f', pos: 1}]

Thanks!

HSLA support?

Nice soft, and useful!
Looking at the doc and the code, I see there's no support for HSL/HSLA colors but only in Hexa.
Could you provide an HSL to RGB module to be able to define gradients with HSL/HSLA?

pause() not always pause the animation

When I call granimInstance.pause(); animation sometimes not paused, but if I check granimInstance.isPaused, this return true.
This happend if I have one granim instance and have 5 buttons which 3 buttons for playing and changing states , one button for pause and one for clear. On different changes I must pressed button for pause twice, for working pause, but on the first time, granimInstance.isPaused, after granimInstance.pause(); return true.
Any idea why is happening this, or how to fix cancel animation Frame work always on first time.

Browser Support

Hey sarcadass,
awesome lib, but one question - what browsers are supported? (is it pure canvas? By default canvas supports >=IE9)

Add example using reactjs

Hi,

I have been trying to use it with reactjs. Everytime I try to load it (on client side after content is loaded), I always get the Uncaught TypeError: this.canvas.getContext is not a function(…) error from Granim.js.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.