색상 팔레트 생성기

Linda Hamilton
풀어 주다: 2024-09-20 06:50:31
원래의
664명이 탐색했습니다.

Colour palette Generator

안녕하세요?? 나는 다시 정상으로 돌아왔다. #100daysofMiva 코딩 챌린지 9일차에는 Nodejs에서 간단한 색상 팔레트 생성기를 작업했습니다. 산책해 보세요...✨

? 색상 팔레트 생성기

확인해 보세요
https://colorpal.onrender.com

이것은 Express.jschroma-js를 사용하여 Node.js로 구축된 색상 팔레트 생성기입니다. 무작위로 생성된 기본 색상의 다양한 색조를 포함하여 매번 아름다운 5색 팔레트를 생성합니다. 빠른 색상 영감을 원하는 UI/UX 디자이너에게 적합합니다! ?

? 특징

  • 단일 기본 색상의 변형으로 일치하는 5가지 색상을 생성합니다.
  • 각 팔레트에는 고유 ID가 할당되어 사용자가 /palette/:id 경로를 통해 팔레트를 검색할 수 있습니다.
  • 서버 측 로직을 위한 Express.js와 색상 조작을 위한 chroma-js로 구축되었습니다.
  • 새 팔레트를 동적으로 생성하는 새로 고침 버튼이 포함된 생성된 팔레트를 표시하기 위한 간단하고 우아한 UI.

백엔드?

?️ 사용된 기술

  • Node.jsExpress.js: 라우팅을 처리하는 백엔드 프레임워크
  • Chroma.js: 강력한 색상 조작 및 팔레트 생성을 위한 도구입니다.
  • HTML/CSS/부트스트랩: 깔끔하고 반응성이 뛰어난 UI를 위한 것입니다.

? 시작하기

1. 리포지토리 복제

git clone https://github.com/Marvellye/colorpal
cd colorpal
로그인 후 복사

2. 종속성 설치

npm install
로그인 후 복사

3. 애플리케이션 실행

node app.js
로그인 후 복사

4. 애플리케이션 열기

브라우저에서 앱을 방문하세요:

http://localhost:3000
로그인 후 복사

새로운 5색 팔레트를 생성할 수 있는 인터페이스가 표시됩니다. 새로운 색상 팔레트를 가져오려면 생성 버튼을 누르세요.

5. ID로 팔레트 검색

특정 팔레트를 검색하려면 다음으로 이동하세요.

http://localhost:3000/palette/:id
로그인 후 복사

:id를 보려는 팔레트의 ID로 바꾸세요. 예:

http://localhost:3000/palette/C08552-F3E9DC-5E3023-DAB49D
로그인 후 복사

? 작동 방식

  1. 팔레트 생성: 생성 버튼을 클릭할 때마다 기본 색상이 무작위로 생성됩니다. 이 베이스를 바탕으로 5가지의 서로 다른 색상 변형(다른 색조)이 생성됩니다.
  2. 고유 ID: 생성된 각 팔레트에는 색상의 16진수 값으로 만들어진 고유 ID가 있으며, 나중에 팔레트를 검색하는 데 사용할 수 있습니다.
  3. Chroma.js 사용: chroma-js의 강력한 기능으로 생성된 색상이 시각적으로 매력적이며 다양한 밝기 수준을 제공합니다.

?️ 예시 팔레트

다음은 앱이 생성하는 팔레트 종류의 예입니다.

Base Color: #C08552
Palette: 
#F3E9DC (Light)
#5E3023 (Dark)
#DAB49D (Neutral)
로그인 후 복사

프론트엔드?✨

? 컬러 팔레트 표시

이 색상 팔레트 생성기는 5가지 색상 팔레트를 동적으로 생성하여 UI에 표시합니다. 사용자는 생성 버튼을 클릭하여 팔레트와 상호 작용할 수 있으며, 팔레트 ID는 특정 색상 조합을 저장하고 공유하는 데 사용됩니다. 레이아웃 작동 방식은 다음과 같습니다.

? HTML 레이아웃

헤더

<!-- Header -->
<header class="p-3 text-center">
   <h1>Colour Palette Generator</h1>
</header>
로그인 후 복사

헤더는 애플리케이션에 대한 깔끔하고 간단한 제목을 제공합니다.

컬러박스

<!-- Colour Boxes -->
<section class="color-container">
   <div id="box1" class="color-box" style="background-color: #000000;">
      <span>#000000</span>
   </div>
   <div id="box2" class="color-box" style="background-color: #000000;">
      <span>#000000</span>
   </div>
   <div id="box3" class="color-box" style="background-color: #000000;">
      <span>#000000</span>
   </div>
   <div id="box4" class="color-box" style="background-color: #000000;">
      <span class="text-white">Hey!</span>
   </div>
   <div id="box5" class="color-box" style="background-color: #000000;">
      <span class="text-white"></span>
   </div>
</section>
로그인 후 복사

이 섹션에는 색상 상자가 포함되어 있습니다. 각 상자는 생성된 색상 팔레트에 따라 배경색을 동적으로 변경하는 div입니다. 각 div 내부의 범위는 색상의 16진수 값을 표시합니다.

짐을 싣는 사람

<!-- Loader -->
<section id="loader" class="loader">
   <div class="is-loading">
      <h3 id="load-text">Generating...</h3>
   </div>
</section>
로그인 후 복사

이 섹션에는 새 색상 팔레트가 생성될 때 나타나는 로더가 포함되어 있습니다. 색상이 로드된 후 로더가 사라집니다.

보행인

<!-- Footer -->
<footer class="d-flex justify-content-between align-items-center">
   <button onclick="gen()" class="btn btn-light">Generate</button>
   <button class="btn text-white" onclick="share(window.location.href)">
      <i class="fa-regular fa-share-from-square"></i>
   </button>
   <span class="">100daysofMiva-Marvelly</span>
</footer>
로그인 후 복사

바닥글에는 색상 생성을 시작하는 생성 버튼과 소셜 미디어 공유를 위한 공유 버튼이 포함되어 있습니다.

? 자바스크립트 기능

동적 색상 생성

const boxes = [
    document.getElementById('box1'),
    document.getElementById('box2'),
    document.getElementById('box3'),
    document.getElementById('box4'),
    document.getElementById('box5')
];

function updateBoxes(colors) {
    colors.forEach((color, index) => {
        boxes[index].style.backgroundColor = color;
        boxes[index].querySelector('span').textContent = color;
    });
}
로그인 후 복사

이 JavaScript 코드는 새 팔레트가 생성될 때 색상 상자의 색상을 동적으로 업데이트합니다. 색상은 UI의 각 div 요소에 적용됩니다.

팔레트 생성 로직

async function gen() {
    // Show the loader
    loader.style.display = 'block';

    try {
        const response = await fetch('/palette');
        const data = await response.json();

        // Update the boxes with the new colors
        updateBoxes(data.palette);

        // Update the URL with the new ID
        history.pushState({}, '', `/${data.id}`);

        loader.style.display = 'none';
    } catch (error) {
        console.error('Error fetching palette:', error);
        loader.style.display = 'none';
    }
}
로그인 후 복사

gen() 함수는 /palette API 경로에서 새 색상 팔레트를 가져오고, 색상 상자를 업데이트하고, 새 팔레트 ID로 브라우저 URL을 수정합니다.

기능 공유

function share(url) {
    Swal.fire({
        heightAuto: false,
        title: 'Share this Color Palette!',
        html: `
            <div style="display: flex; justify-content: space-around; font-size: 24px;">
                <a href="https://api.whatsapp.com/send?text=${encodeURIComponent(url)}" target="_blank" title="Share on WhatsApp">
                    <i class="fab fa-whatsapp" style="color: #25D366;"></i>
                </a>
                <a href="https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(url)}" target="_blank" title="Share on Facebook">
                    <i class="fab fa-facebook" style="color: #3b5998;"></i>
                </a>
                <a href="https://twitter.com/intent/tweet?url=${encodeURIComponent(url)}" target="_blank" title="Share on Twitter">
                    <i class="fab fa-twitter" style="color: #1DA1F2;"></i>
                </a>
                <a href="https://www.instagram.com/?url=${encodeURIComponent(url)}" target="_blank" title="Share on Instagram">
                    <i class="fab fa-instagram" style="color: #E1306C;"></i>
                </a>
            </div>
        `,
        showConfirmButton: false,
        showCloseButton: false,
    });
}
로그인 후 복사

share() 기능을 사용하면 사용자는 SweetAlert 팝업을 사용하여 WhatsApp, Facebook, Twitter, Instagram, Telegram과 같은 소셜 미디어 플랫폼을 통해 현재 색상 팔레트를 공유할 수 있습니다.

URL-Based Color Loading

// Check if an id is present in the URL
const currentPath = window.location.pathname;
const paletteId = currentPath.substring(1);

if (paletteId) {
    loadPaletteById(paletteId);
} else {
    gen();
}
로그인 후 복사

This functionality checks if there is a color palette ID in the URL when the page is loaded. If an ID is present, the corresponding palette is loaded. Otherwise, a new palette is generated.

? Issues Encountered

Building this app wasn't without its challenges! Here are some of the problems I encountered and how I solved them:

  1. Dull Color Palettes: Initially, I was getting dull and boring colors. The issue was due to the way I was generating shades from the base color. I switched to using hsl.l (lightness) adjustments for better visual results.

  2. Color Palette Variants: At first, I used random colors that were too different from each other. After realizing that everyone needed variants of the same base color for consistency, I adjusted my approach to generate color scales with different lightness levels.

  3. Invalid Palette IDs: When trying to retrieve a palette by ID, some IDs were invalid or incorrectly formatted. I fixed this by ensuring a strict format for the IDs and adding error handling for invalid IDs.

  4. Hex Values Misplacement: At one point, the hex values were not displaying properly inside the color boxes. This was fixed by ensuring the span elements were correctly updated with the hex values.

  5. Palette Sharing: Creating a robust sharing mechanism for various social media platforms was a bit challenging but ultimately solved using SweetAlert for the UI and share links for each platform.

  6. Dynamic Palette Update: Implementing a smooth update of the UI when a new palette was generated was tricky. By using simple JavaScript and handling the loader display correctly, I ensured a seamless experience for users when generating new palettes.

✨ Future Improvements

  • Add support for saving favorite palettes in a database.
  • Enhance the UI with animations for palette generation.
  • Allow users to download the color palette in various formats like JSON, CSS, or an image.

Check it out
https://colorpal.onrender.com

My GitHub repo
https://github.com/Marvellye/colorpal

위 내용은 색상 팔레트 생성기의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!