Skip to content

Instantly share code, notes, and snippets.

@ayaysir
Created December 22, 2019 16:25
Show Gist options
  • Save ayaysir/d43d7f51204a3f2fdb49e012ca8786a2 to your computer and use it in GitHub Desktop.
Save ayaysir/d43d7f51204a3f2fdb49e012ca8786a2 to your computer and use it in GitHub Desktop.
피자 n등분 프로그램
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Pizza</title>
</head>
<body onload="draw();">
<canvas width="300" height="300" id="canvas"></canvas>
<input type="number" min="1" max="360" id="input-part" value="5">
<script>
// 설정 변수
const geom = {
x: 150,
y: 150,
radius: 110,
statrAngle: 0,
endAngle: 360,
anticlockwise: false
}
// 각도(degree)를 라디안(radian)으로 변환
function degToRad(deg) {
return (Math.PI / 180) * deg
}
// 2d 컨텍스트에 원을 n등분하여 그림
function divCircle(ctx, part) {
const eachDeg = 360 / part // n등분 할 경우 각 부분의 각도
const lineWidth = part <= 8 ? 6 : part <= 16 ? 3 : 1
if (part == 1) {
// 1등분인 경우 원을 나눌 필요가 없으므로 단일의 원을 그리고 종료
ctx.beginPath()
ctx.arc(geom.x, geom.y, geom.radius, degToRad(0), degToRad(360), geom.anticlockwise)
ctx.closePath()
ctx.fillStyle = `rgba(${Math.random() * 255}, ${Math.random() * 255}, ${Math.random() * 255}, 0)`
ctx.fill()
} else {
for (let i = 0; i <= part; i++) {
ctx.beginPath() // 경로 시작
ctx.lineWidth = lineWidth
ctx.strokeStyle = "rgba(0, 0, 0, 1)"
// arc(x, y, radius, startAngle, endAngle, anticlockwise)
ctx.arc(geom.x, geom.y, geom.radius, degToRad(i * eachDeg), degToRad(i * eachDeg + eachDeg), geom.anticlockwise)
ctx.lineTo(geom.x, geom.y) // 특정 좌표 위치로 선을 그림
ctx.closePath() // 경로 종료
ctx.fillStyle = `rgba(${Math.random() * 255}, ${Math.random() * 255}, ${Math.random() * 255}, 0)`
ctx.fill() // 채우기
ctx.stroke() // 윤곽선 그리기
}
}
}
// 캔버스를 초기화
function resetCanvas(canvas, cbFunc) {
const ctx = canvas.getContext("2d")
ctx.clearRect(0, 0, canvas.width, canvas.height) // 캔버스를 지우고 초기화
const image = new Image() // 이미지 객체 생성
image.src = getPizzaBase64()
image.onload = _ => {
ctx.drawImage(image, 0, 0) // 이미지 파일 내용을 캔버스 컨텍스트에 배치
cbFunc()
}
}
// canvas가 로딩되면 실행되는 함수
function draw() {
const canvas = document.getElementById("canvas")
const ctx = canvas.getContext("2d")
const numField = document.getElementById("input-part")
const cbFunc = _ => {
divCircle(ctx, numField.value)
}
resetCanvas(canvas, cbFunc)
numField.onchange = e => {
resetCanvas(canvas, cbFunc)
}
}
// 피자 그림 (Base64)
function getPizzaBase64() {
return "./pizza.png"
}
</script>
</body></html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment