한 걸음씩

[JS] Canvas 1 - making canvas 본문

JS

[JS] Canvas 1 - making canvas

winter17 2023. 6. 30. 22:58

▷ canvas HTML 태그를 사용하려면 body 안에 canvas 태그를 아래와 같이 넣어줘야 한다.

// index.html
<body>
  <canvas></canvas>

  <script src="app.js"></script>
</body>

 

▷ css 파일에서 canvas 사이즈를 정하고 테두리를 만들어 준다.

// styles.css
canvas{
  width: 700;
  height: 700;
  border: 5px solid black;
  background-color: skyblue;
}

▷ JS 파일에서 canvas에 그림을 그릴 수 있도록 코드를 작성하면 된다. 

▷ 우선 canvas 태그를 불러와서 getContext로 2d를 가져와야 한다. 

▷ 그리고 css에서 너비와 높이를 설정했지만 js파일에서 한 번 더 설정해줘야 한다.

const canvas = document.querySelector('canvas')
const ctx = canvas.getContext('2d')
const CANVASE_WIDTH = 700
const CANVAS_HEIGHT = 700
canvas.width = CANVASE_WIDTH
canvas.height = CANVAS_HEIGHT

https://developer.mozilla.org/ko/docs/Web/API/Canvas_API/Tutorial/Basic_usage

 

캔버스(Canvas) 기본 사용법 - Web API | MDN

<canvas> HTML 엘리먼트를 살펴보는 것으로 이 튜토리얼을 시작해 보겠습니다. 이 페이지의 끝에서 캔버스 2D 컨텍스트를 설정하는 방법을 알게되고, 여러분의 브라우저에서 첫 번째 예제를 그리게

developer.mozilla.org

 

 

// index.html
// 위의 html 파일에서 추가적인 부분 작성
<body>
  <canvas></canvas>
  
  <input type="range" id="line-width" min="1" max="10" step="0.5" value="5">
  <input type="color" id="color">
  
  <div>
    <div class="color" style="background-color: #1abc9c" data-color = "#1abc9c"></div>
    <div class="color" style="background-color: #3498db" data-color= "#3498db"></div>
    <div class="color" style="background-color: #34495e" data-color= "#34495e"></div>
    <div class="color" style="background-color: #27ae60" data-color= "#27ae60"></div>
    <div class="color" style="background-color: #8e44ad" data-color= "#8e44ad"></div>
    <div class="color" style="background-color: #f1c40f" data-color= "#f1c40f"></div>
    <div class="color" style="background-color: #e74c3c" data-color= "#e74c3c"></div>
    <div class="color" style="background-color: #95a5a6" data-color= "#95a5a6"></div>
    <div class="color" style="background-color: #d35400" data-color= "#d35400"></div>
    <div class="color" style="background-color: #bdc3c7" data-color= "#bdc3c7"></div>
    <div class="color" style="background-color: #2ecc71" data-color= "#2ecc71"></div>
    <div class="color" style="background-color: #e67e22" data-color= "#e67e22"></div>
  </div>
  <button id="mode-btn">Fill</button>
  <button id="clear">clear</button>
  <button id="eraser">Erase</button>
  <script src="app.js"></script>
</body>

 

// styles.css
// 위의 css파일에서 추가적인 부분 작성
body{
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.color{
  cursor: pointer;
  width: 50px;
  height: 50px;
}
button{
  width: 50px;
  height: 50px;
}

이러한 이미지를 만들기 위해서는 다음과 같은 코드가 필요하다.

// home & human
ctx.fillRect(200, 200 + 200, 50, 200)
ctx.fillRect(400, 200 + 200, 50, 200)
ctx.fillRect(300, 300 + 200, 50, 100)
ctx.fillRect(200, 200 + 200, 200, 20)
ctx.moveTo(200, 200 + 200)
ctx.lineTo(325, 100 + 200)
ctx.lineTo(450, 200 + 200)
ctx.fill()

ctx.fillRect(600, 200 + 40 + 200, 50, 100)
ctx.fillRect(575, 200 + 40 + 200, 20, 50)
ctx.fillRect(655, 200 + 40 + 200, 20, 50)
ctx.fillRect(600, 305 + 40 + 200, 20, 50)
ctx.fillRect(630, 305 + 40 + 200, 20, 50)

ctx.beginPath()
ctx.arc(625, 170 + 40 + 200, 25, 0, 2 * Math.PI)
ctx.fill()

ctx.beginPath()
ctx.fillStyle = 'white'
ctx.arc(615, 165 + 40 + 200, 3, Math.PI, 2 * Math.PI)
ctx.arc(627, 165 + 40 + 200, 3, Math.PI, 2 * Math.PI)
ctx.fill()

ctx.beginPath()
ctx.fillStyle = 'green'
ctx.fillRect(0, 600, 700, 100)

 

fillRect(x좌표, y좌표, 너비, 높이) : fillRect은 사각형을 만들고 채우기 역할을 하는 것이다.

fillStyle : 채울 색상의 스타일

moveTo(x좌표, y좌표) : 시작점을 알림, 펜을 x와 y로 지정된 좌표로 옮김

lineTo(x좌표, y좌표) : moveTo의 위치에서 lineTo에 지정한 위치까지 선을 그림

beginPath() : 새로운 경로를 만듦

arc(x, y, radius, startAngle, endAngle, anticclockwise) : 호나 원을 그리기 위해서 사용함. (x, y)위치에 점을 두고 반지름 radius을 가지고 startAngle에서 시작하여 endAngle에서 끝나며 주어진 anticlockwise 방향으로 향하는 호를 그린다. 

fill : 해당하는 경로의 내부를 채운 도형을 그림

https://developer.mozilla.org/ko/docs/Web/API/Canvas_API/Tutorial/Drawing_shapes

 

캔버스(canvas)를 이용한 도형 그리기 - Web API | MDN

앞서 캔버스 환경 설정(canvas environment)을 완료 하였다면, 이제 어떻게 캔버스에 그릴수 있는지에 대하여 자세하게 알아봅시다. 이 글을 끝내고 난 후, 여러분은 어떻게 사각형, 삼각형, 선, 아치,

developer.mozilla.org

 

 

 

▷ canvas 그림판 만들기 (그리기, 지우기, 전체 지우기)

 

화면 기록 2023-06-30 오후 10.35.20.mov
13.05MB

// painting
const lineWidth = document.querySelector('#line-width')
const color = document.querySelector('#color')
const colorOptions = document.querySelectorAll('.color')
const modeBtn = document.querySelector('#mode-btn')
const clear = document.querySelector('#clear')
const erase = document.querySelector('#eraser')

ctx.beginPath()
let isPainting = false
let isFilling = false

ctx.lineWidth = lineWidth.value
ctx.strokeStyle = color.value

// 마우스를 움직일 때
function onMouseMove(e){
  if (isPainting){
    ctx.lineTo(e.offsetX, e.offsetY)
    // offset은 마우스 이벤트 객체에 포함된 속성이고 마우스 커서의 위치를 나타낸다.
    ctx.stroke()
    // return은 함수를 즉시 종료하는 역할을 하는데 return의 유무가 동작에 영향을 미치지는 않지만
    // 유지보수와 가독성에 영향을 미치기 떄문에 작성하는것이 권장된다.
    return
  }
  ctx.moveTo(e.offsetX, e.offsetY)  
  // moveTo가 시작점이 되어 lineTo 지점까지 선을 그린다.
}
// 마우스를 눌렀을 때 시작
function startPainting(){
  isPainting = true
}
 // 마우스를 뗐을 때
function endpainting(){
  isPainting = false
  ctx.beginPath() // 그리기 동작이 끝나면 초기화 (선 굵기를 업데이트 하기 위함)
}
 // 선 굵기 조절 (HTML 파일에서 input range로 범위 조절)
function onLineWidthChange(e){
  ctx.lineWidth = e.target.value
}
// 선, 채우기 색상(사용자 선택)
function onColorChange(e){
  ctx.strokeStyle = e.target.value
  ctx.fillStyle = e.target.value
}
// 컬러칩 12가지 중 하나 선택해서 색상 변경
function onClickColor(e){
  const dataSetColor = e.target.dataset.color
  ctx.strokeStyle = dataSetColor
  ctx.fillStyle = dataSetColor
  color.value =  dataSetColor
}
// Fill / Draw 모드 선택해서 실행
function onModeClick(){
  if (isFilling){ // 채우기 모드인 경우
    isFilling = false // 채우기 모드 비활성화
    modeBtn.innerText = 'Draw' // Draw로 전환
  }else{ // 그리기 모드
    isFilling = true // 채우기 모드 활성화
    modeBtn.innerText = 'Fill' // Fill로 전환
  }
}
// 캔버스를 클릭하면 캔버스 전체 색상이 변경
function onCanvasClick(){ 
  if (isFilling){
    ctx.fillRect(0, 0, CANVASE_WIDTH, CANVAS_HEIGHT)
  }
}
// 클리어 버튼 누르면 캔버스가 화이트 색상으로 변경
function onClearClick(){
  ctx.fillRect(0, 0, CANVASE_WIDTH, CANVAS_HEIGHT)
  ctx.fillStyle = 'white'
}
// 지우기 버튼을 클릭하면 하얀색 지우개가 나타나도록 설정
function onEraserClick(){
  ctx.strokeStyle = 'white'
  isFilling = false // 채우기 모드 비활성화
  modeBtn.innerText = 'Draw' // Draw로 전환
}

canvas.addEventListener('mousemove', onMouseMove)// 마우스를 움직일 때
canvas.addEventListener('mousedown', startPainting)// 마우스를 눌렀을 때 시작
canvas.addEventListener('click', onCanvasClick) // 캔버스를 클릭하면 캔버스 전체 색상이 변경

// mouseup 이벤트만 실행하면 캔버스를 벗어나도 그리기 상태가 유지되는 버그가 발생한다.
// mouseleave 이벤트를 설정하여 마우스가 캔버스를 벗어날 경우 그리기 동작을 멈추도록 할 필요가 있다.
canvas.addEventListener('mouseup', endpainting) // 마우스를 뗐을 때
canvas.addEventListener('mouseleave', endpainting)// 마우스가 캔버스를 벗어났을 경우

lineWidth.addEventListener('change', onLineWidthChange)// 선 굵기 설정
color.addEventListener('change', onColorChange) // 컬러 선택
// 12가지 컬러칩; forEach로 순회하여 이벤트 실행
colorOptions.forEach(colorOption => colorOption.addEventListener('click', onClickColor))
modeBtn.addEventListener('click', onModeClick) // Fill / Draw모드
clear.addEventListener('click', onClearClick) // 모두 지우기
erase.addEventListener('click', onEraserClick) // 지우개

https://github.com/winterkang/JavaScript-Challenge/tree/main/canvas


그림판 만들기 어려울 줄 알았는데 투두리스트나 계산기 만들기보다 훨씬 간단한 것 같다.

'JS' 카테고리의 다른 글

[JS] weather API and Date  (0) 2023.07.02
[JS] canvas 2 - meme maker, text, save  (0) 2023.07.01
[JS] keydown, keyup, keypress  (0) 2023.06.20
[JS] 'this' 키워드  (0) 2023.06.03
[JS] do~while문, continue문  (0) 2023.06.02