How to change font color based on background color using reactJs

ぃ、小莉子 提交于 2020-08-10 05:18:50

问题


I have dynamic background of my container it will change by User so I need to set text color based of background color eg, I set black background of my container then i need to set white color for text, I am using ReactJs and material UI library for my App, please suggest some good path.


回答1:


see the below sample code.

import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
import DynamicContainer from "./style";

import "./styles.css";

function App() {
  const [bgColor, setBGColor] = useState("#422DAD");
  const [textColor, setTextColor] = useState("rgb(99,99,100)");

  function hexToRgb(hex) {
    // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
    var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
    hex = hex.replace(shorthandRegex, function(m, r, g, b) {
      return r + r + g + g + b + b;
    });

    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    return result
      ? {
          r: parseInt(result[1], 16),
          g: parseInt(result[2], 16),
          b: parseInt(result[3], 16)
        }
      : null;
  }

  useEffect(() => {
    let { r, g, b } = hexToRgb(bgColor);
    let targetColor = `rgb(${r},${g},${b})`;
    var colors = targetColor.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
    var brightness = 1;

    var R = colors[1];
    var G = colors[2];
    var B = colors[3];

    var ir = Math.floor((255 - R) * brightness);
    var ig = Math.floor((255 - G) * brightness);
    var ib = Math.floor((255 - B) * brightness);
    setTextColor(`rgb(${ir}, ${ig}, ${ib})`);
  }, [bgColor]);

  const handleBgChange = e => {
    setBGColor(e.target.value);
  };

  return (
    <>
      <DynamicContainer bgColor={bgColor} textColor={textColor}>
        Hello World!
      </DynamicContainer>
      <p>Choose Background color</p>
      <input type="color" value={bgColor} onChange={handleBgChange} />
    </>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

here is the upadted codesandbox

check here



来源:https://stackoverflow.com/questions/59193701/how-to-change-font-color-based-on-background-color-using-reactjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!