카테고리별 건수 및 비중 시각화

기여·2024년 8월 21일
0

소소한 개발팁

목록 보기
82/103

희망사항:

  • 카테고리별 제품 건수 및 비중 계산
  • 비중은 소수점 첫째 자리로 반올림
  • 해당 비중에 비례하는 길이의 바 형태로 시각화
  • 색상은 랜덤 적용하는데, 파스텔 톤 위주로 😸

Vo

private int prdCntByCtgr; //카테고리별 제품 건수
private double percentage; //카테고리별 제품 비중

Mapper

//카테고리별 제품 건수 및 비중
		@Select("SELECT category, "
				+ "COUNT(product_code) AS prdCntByCtgr, "
				+ "ROUND(COUNT(product_code) / (SELECT COUNT(*) FROM products) * 100, 1) AS percentage "
				+ "FROM products "
				+ "GROUP BY category")
		List<PrdVo> countByCtgr();

Ctrl

@GetMapping("prdList") //상품 리스트 관리
	public String prdList(Model model, PrdVo vo) {
		...
		//카테고리별 제품 건수 및 비중
		List<PrdVo> cntLi=prdSvc.countByCtgr();
		model.addAttribute("cntLi", cntLi);
		
		return "prd/prdList";
	}

html (바 부분만)

<div id="category" style="width: 100%; display: flex; margin-bottom: 30px;">
    <div th:each="cnt : ${cntLi}" id="eachCategory"
         th:style="'width:' + ${cnt.percentage} + '%; display: flex; align-items: center; 
         justify-content: center; padding: 5px; text-align: center; border-right: 1px solid #ffffff;'">
         
        <a th:text="'#' + ${cnt.category} + ' (' + ${cnt.prdCntByCtgr} + '건, ' + ${cnt.percentage} + '%)'" 
           th:href="@{/prd/prdListByCtgr(category=${cnt.category})}" 
           style="color: #555; text-decoration: none; font-size: 14px;"></a>
    </div>
</div>

js)

  • 파스텔 톤 적용할 경우:
<script>
    document.addEventListener('DOMContentLoaded', function() {
        const categories = document.querySelectorAll('#eachCategory');

        categories.forEach(function(category) {
            const pastelColor = generatePastelColor();
            category.style.backgroundColor = pastelColor;
        });

        // 파스텔 색상 생성 함수
        function generatePastelColor() {
            const r = Math.floor((Math.random() * 127) + 127);  // 127 ~ 255 범위에서 랜덤 값 (밝은 빨강)
            const g = Math.floor((Math.random() * 127) + 127);  // 127 ~ 255 범위에서 랜덤 값 (밝은 초록)
            const b = Math.floor((Math.random() * 127) + 127);  // 127 ~ 255 범위에서 랜덤 값 (밝은 파랑)

            return `rgb(${r}, ${g}, ${b})`;
        }
    });
</script>
  • 원색으로도 만족할 경우:
<script>
    document.addEventListener('DOMContentLoaded', function() {
        const categories = document.querySelectorAll('#eachCategory');

        categories.forEach(function(category) {
            const randomColor = '#' + Math.floor(Math.random() * 16777215).toString(16);
            category.style.backgroundColor = randomColor;
        });
    });
</script>

가끔 별 기대 없이 물어보는데 오히려 아주 만족스러운 답변 받을 때가 많다~!

Math.floor((Math.random() * 127) + 127):
각 색상 성분(R, G, B)을 127 이상으로 설정하여 채도가 낮고 밝은 색을 생성합니다.
이 범위는 127부터 255까지이며, 127을 더해서 최소한의 밝기를 보장합니다.
파스텔 톤: 파스텔 색상은 기본적으로 매우 밝기 때문에,
각 RGB 값이 높은 값에 가까운 범위에서 랜덤하게 설정됩니다.

아이디어는 아이폰 저장공간을 참고했다.

profile
기기 좋아하는 여자

0개의 댓글