Help us understand the problem. What is going on with this article?

styled-componentsとhue-rotateで1枚の画像を怠惰にカラフルにする

More than 1 year has passed since last update.

何らかのMockを作るときなど、アバターアイコンを色々配色させたいことがある。
Twitterの昔あった卵アイコンみたいなやつ。
styled-componentsとcssのhue-rotateを利用すると雑にpng一枚用意するだけで出来る。

↓こんな感じにできる。
React_App.png

「SVGでやったほうがいいんだけどちょっとだるい」みたいなときにおすすめ。
実装とか色々考えると圧倒的にsvgとかでやったほうがいいので繋ぎの手段としてどうぞ。

あと今回はstyled-componentsでやっているが、CSSの機能なのでsassとかでも出来るはず。
styled-components使うことで動的に処理できるという点が旨味

実装

例えばこんな画像を用意する
icon.png

で、こんな具合に実装。

import React, { Component } from "react";
import icon from "./icon.png";
import styled from "styled-components";

const randomAngle = () => {
  const num = 7; // ランダムに出したい色数
  return (Math.ceil(Math.random() * num) * 360) / num;
};

// ここでhue-rotate使う
const MockAvater = styled.img`
  filter: hue-rotate(${() => `${randomAngle()}deg`});
`;

class App extends Component {
  render() {
    return (
      <div className="App">
        <MockAvater src={icon} width="80" />
      </div>
    );
  }
}

もし「色数は変数を渡したい」みたいな場合であればこんな感じ

const getAngle = (idx, max) => {
  console.log(idx);
  return (360 * idx) / max;
};
const MockAvaterManual = styled.img`
  filter: hue-rotate(${({ idx, max }) => `${getAngle(idx, max)}deg`});
`;

class App extends Component {
  render() {
    return (
      <MockAvaterManual src={icon} width="80" max={8} idx={0} />
    )
  }
}
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした