-
[Canvas] Color-pickerHtml Canvas 2022. 3. 4. 11:30
HTML Color-picker 만들기
컨버스에 이미지를 띄운 다음, 이미지에 마우스를 가져가면 해당 마우스 포인터의 색깔을 추출해서 알려준다.
이는 2가지 로직만 알고 있으면 쉽게 구현할 수 있다.
1. 캔버스에 이미지 삽입하기와 같은 방식으로 캔버스 ctx 에 이미지를 삽입 할 수 있으며, drawImage 는 여러 속성이 있으므로 때에 따라 골라서 사용할 수 있다.
this.img = new Image(); this.img.src = "./starryNight.jpeg"; this.img.onload = () => { this.ctx.drawImage(this.img, 0, 0); };
2.마우스 위치에 있는 컬러 추출하기getImageData(mouseX, mouseY, 1, 1); 로 마우스가 있는 곳의 이미지 픽셀 데이터를 가져올 수 있으며 해당 픽셀 데이터는 4개의 r,g,b,a 로 구성된 배열이다.
pick(event, message) { this.ctx.clearRect(0, 0, this.stageWidth, this.stageHeight); this.ctx.drawImage(this.img, 0, 0); const x = event.layerX; const y = event.layerY; const pixel = this.ctx.getImageData(x, y, 1, 1); const data = pixel.data; const rgba = `rgba(${data[0]},${data[1]},${data[2]},${data[3] / 255})`; this.ctx.font = "40px serif"; this.ctx.fillStyle = `${rgba}`; this.ctx.fillText(`${message}: ${rgba}`, 10, this.img.height + 50); }
reference
https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API
'Html Canvas' 카테고리의 다른 글
오브젝트 풀링 [펌] (0) 2022.06.22 [Html canvas] devicepixelRatio 를 사용해 선명한 이미지 렌더링하기 (0) 2022.06.17