反応を用いた動的勾配発生器js


傾斜発電機は楽しいようです.私は主にmycolorを使用します.スペースのWebサイト別の形式でグラデーションを生成します.週末は自分のグラデーションジェネレータを作ることにしました.スペース.ここでデモを見てください.
ここでプロジェクトのソースコードとここでのライブデモを見つけることができます.


グラデーションジェネレータの方向と色を変更するためのオプションがあります.それは色のパラメータにかかり、それらの間に最も関連する3色を生成します.

環境を準備する


まず第一に、作成反応アプリを使用して反応アプリを作成し、TailWindCSSのサポートを追加します.
npx create-react-app color-generator-react
cd color-generator-react
さて、プロジェクトにCDを入れて、クロマJSである唯一の依存関係を加えてください.
yarn add chroma-js
OR
npm install chroma-js

を追加する


yarn add -D tailwindcss postcss autoprefixer
OR
npm install -D tailwindcss postcss autoprefixer
下のコードはtailwindcss.config.js ファイル.我々が通過したので-p また、postcss.config.js TailWindCSSで使用するデフォルトの設定ファイル.
npx tailwindcss init -p
では、Aを作成しましょうtailwind.css 資産フォルダのファイル.
mkdir assets
cd assets
touch tailwind.css // Linux
OR 
echo. > tailwind.css // Windows
作成したtailwind.css 以下のTailWindCSSディレクティブを追加します.
@tailwind base;
@tailwind components;
@tailwind utilities;
おめでとう、TarwindCSSは正常にプロジェクトに追加されます.
TailWindCSSが追加されると、プロジェクトに取り組むことができます.しかし、その前に、chroma jsの少しの導入をしましょう.

クロマJS入門


クロマJSは、それがカラー操作、変換とスケーリングに来るとき、ソフトウェアの驚くべき部分です.それはあなたが暗いか、色相操作に明るくから操作のあらゆる種類のために必要なすべてを持っています.また、別の色空間で結果を与える.それを読むことができます変換、分析し、さまざまな形式に色を操作します.
我々は、実際の与えられた2つのパラメータから3つ以上の色を生成し、5色のグラデーションを作成するためにchroma jsを使用するつもりです.

レイアウトを作ろう


シンプルさのために単一の主要なコンポーネントだけがあります.下のマークアップはdiv Flexboxプロパティを使用して中心に.
    <div className="flex items-center bg-gray-900 justify-center md:fixed h-screen inset-0 px-10">
    /* All the content is centered. */
    </div>
色の広がりの方向を変更するコントロールを作成するには、次のコードをApp.js ファイル.

          <div className="flex items-center justify-center p-2 gap-2 flex-wrap md:gap-5">

              <button title="to top" onClick={() => changeOrientation("to top") }>
              <img src={arrow} alt="arrow to top" />
              </button>

              <button title="to right top" onClick={() => changeOrientation("to right top") }>
              <img src={arrow} alt="arrow to right top" className="transform rotate-45" />
              </button>

              <button title="to right" onClick={() => changeOrientation("to right") }>
              <img src={arrow} alt="arrow to right" className="transform rotate-90" />
              </button>

              <button title="to right bottom" onClick={() => changeOrientation("to right bottom") }>
              <img src={arrow} alt="arrow to right bottom" className="rotate-135" />
              </button>

              <button title="to bottom" onClick={() => changeOrientation("to bottom") }>
              <img src={arrow} alt="arrow to bottom" className="transform rotate-180" />
              </button>

              <button title="to bottom left" onClick={() => changeOrientation("to bottom left") }>
              <img src={arrow} alt="arrow to bottom left" className="rotate-225" />
              </button>

              <button title="to left" onClick={() => changeOrientation("to left") }>
              <img src={arrow} alt="arrow to left" className="transform -rotate-90" />
              </button>

              <button title="to left top" onClick={() => changeOrientation("to left top") }>
              <img src={arrow} alt="arrow to left top" className="transform rotate-180" />
              </button>

              <button onClick={() => changeOrientation("circle") }>
              <img src={radial} alt="radial" className="px-1.5" />
              </button>

          </div>

それらのいくつかを回転させるためにApp.css ファイル.
.rotate-135 {
    transform: rotate(135deg);
}

.rotate-225 {
    transform: rotate(225deg);
}
button:focus{
    border: 2px solid white;
    border-radius:50%;
    outline: none;
    transition: all 220ms ease-in;
}

これは次のようになります.
![方向制御]
ユーザーからのカラー入力と下の小さなCSSコードボックスをとるために、2つのボタンをたった今加えましょう.
<h2 className="text-xl text-white text-center py-3 mt-5 italic font-cursive">Enter Colors & press Enter.</h2>
<div className="text-white text-center py-2 rounded mb-3  text-white w-40 mx-auto">
  <h2 className="bg-amber-700">{error}</h2>
</div>


<div className="flex items-center justify-center flex-wrap">
    <form className="flex gap-5 justify-center items-center flex-wrap">

        <input type="text"
             ref={hex}
             defaultValue={color1}
             style={icolor1}
             className="rounded px-2 py-3 text-center shadow-2xl font-bold bg-red-900" 
             name="hex" />

        <input type="text"
             ref={hex2}
             defaultValue={color2}
             style={icolor2}
             className="rounded px-2 py-3 text-center shadow-2xl font-bold bg-red-700" 
             name="hex2"/>

        <input
              type="submit"
              className="hidden"
              onClick={(e) => doJob(e)}
              />

      </form>
</div>

  <div className="box md:w-[640px] w-[350px] h-auto mx-auto break-all mt-4 p-2 ">
      <p className="p-3 text-gray-200 font-mono text-base md:text-xl text-center font-semibold">
          <span className="text-gray-100">background-image: </span> { cssCode }
      </p>
  </div>

.font-cursive {
    font-family: cursive;
}

.box{
    background: rgba( 255, 254, 254, 0.05 );
    box-shadow: 0 8px 32px 0 rgba( 31, 38, 135, 0.37 );
    backdrop-filter: blur( 9.5px );
    -webkit-backdrop-filter: blur( 9.5px );
    border-radius: 10px;
    border: 1px solid rgba( 255, 255, 255, 0.18 );
}
マークアップとCSSを追加すると、このようになります.今この瞬間、我々はアプリケーションの基本的なレイアウトを構築し終えている.
markup-complete-tutorial

機能の追加


まず第一に、色とボタンのためにすべての変数とrefsを宣言しなければなりません.反応機能コンポーネントの状態を使用するには、USENTフックを使用します.

    const [color1, setColor1] = useState("#FF6347"); //input box one default color
    const [color2, setColor2] = useState("#0000FF"); //input box2 one default color

    //dynamically generated colors using chroma js
    const [generated1, setGenerated1] = useState("");
    const [generated2, setGenerated2] = useState("");
    const [generated3, setGenerated3] = useState("");

  //css controls
    const [direction, setDirection] = useState("linear-gradient");
    const [orientation, setOrientation] = useState("to right bottom");

    //errors var
    const [error, setError] = useState("")

  //color vars for dynamic color for the input text
    const [invertedcolor1, setinvertedColor1 ] = useState("")
    const [invertedcolor2, setinvertedColor2 ] = useState("")

    //refs to both the inputs
    const hex = useRef(color1);
    const hex2 = useRef(color2);

  //String style built for the div background to display the gradient color
  const ulStyle = { backgroundImage: direction + "("+orientation+","+color1 +","+generated1 +","+generated2 +","+generated3 +","+color2+")"}

  //string generated to copy by the user
    const cssCode = direction+ "("+orientation+","+color1 +","+generated1 +","+generated2 +","+generated3 +","+color2+");";


さて、矢印ボタンが選択されると、次のように渡される方向文字列で関数の変更方向が解凍されます.
<button title="to right" onClick={() => changeOrientation("to right") }>
              <img src={arrow} alt="arrow to right" className="transform rotate-90" />
</button>

関数を扱うには、以下の関数を書きます.

    const changeOrientation = function (ori){

    //condition to check if the passed in string is circle
    //if circle the radial gradient is generated
    //else linear gradient

        if(ori === "circle"){
          //setting the direction variable & orientation
            setDirection("radial-gradient")
            setOrientation(ori)
        }else{
            setDirection("linear-gradient")
            setOrientation(ori)
        }

    }

現在、背景色が何かであるとき、我々はダイナミックに背景色に基づいて暗いか明るい色に入力ボックス色をセットしなければなりません.同様に、ユーザーの入力から動的な色を3つ生成する必要があります.関数を以下のように扱う.

  //the background color and text color style for inputs
  const icolor1 = { background: color1, color:invertedcolor1 }
    const icolor2 = { background: color2, color:invertedcolor2 }

    function checkContrast(color){

                //checking the luminance of the color
                const contrast = chroma(color).luminance();

        //returning the color based on the luminance of the background
                if(contrast > 0.6){
                    return "#000"
                }else{
                    return "#fff"
                }
    }
ダイナミックカラージェネレータ機能.

const generateColors = function () {
    //check if both the colors are valid colors
        if(chroma.valid(color1) && chroma.valid(color2)){

      //use the chroma-js scale feature to interpolate
      //between two color values and generate 3 more
      //dynamic colors including both input colors

            let word = chroma.scale([color1,color2])
                .mode('lch').colors(5);

      //set the generated colors.
      //Due to just 3 colors, I did not use loop.
            setGenerated1(word[1]);
            setGenerated2(word[2]);
            setGenerated3(word[3]);

      //At this moment, setting the text color of the input boxes
            setinvertedColor1(checkContrast(color1))
            setinvertedColor2(checkContrast(color2))

      //Setting the error to empty string
            setError("")

        }else{
          //if not set the error
            setError("Color are no valid.")
        }

    }

今、誰かが色を入力し、Enterボタンを押すとdoJob(e) ここでイベントはパラメータに渡されます.
    function doJob(e){
        //prevents default submission of the form
        e.preventDefault();
        //setting new values of the input colors
        //everything else changes on their own as the
        //values are reactive
        setColor1(hex.current.value);
        setColor2(hex2.current.value);

    }
  //use the hook instead of componentDidMount 
    useEffect(() => {
      //generating colors on the mount
        generateColors();
    });

アプリを使用して実行yarn start or npm run start そして、localhostでアプリケーションの出力を見るべきです.
final-output