펜의 굵기 정하기
-만들고 싶은 기능
- html에 먼저 input을 만들어준다.
- input의 종류는 range
- 가장 작은 값은 1, 큰 값은 15로 설정해주었고 기본값은 5로 주었다.
<body>
<canvas></canvas>
<input id="line-width" type="range" min="1" max="15" value="5"/>
<script src="./app.js"></script>
</body>
- JS에서 html의 input값을 가져온다.
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
//값 가져오기
const lineWidth = document.querySelector("#line-width");
ctx.lineWidth = lineWidth.value;
- 그다음에 값이 바뀔때마다 적용시킨다.
lineWidth.addEventListner("change", onLineWidthChange);
// event에서 value값을 가져오면 input의 값을 가져올 수 있음! (바뀐값을 가져와야하니까)
function onLineWidthChange(event){
ctx.lineWidth = event.target.value;
}
- 수정하고 나면 위처럼 펜의 굵기가 바뀌긴 하지만, 이전의 펜과 같이 바뀌므로 오류 수정이 필요하다.
- 이건 펜의 연결을 끊어주면 되므로 두가지 방법이 있다.
- 1) 마우스가 up될때마다 새로운 선을 만들어준다.
function onMouseUp() {
//클릭이 떨어졌다는 신호
isPainting = false;
ctx.beginPath();
}
- 2) 아니면 마우스가 move될 때, 움직이기 전에 새로운 선임을 설정해준다.
function onMove(event) {
// 만약에 눌렸다면 그려주세요.
if (isPainting) {
ctx.lineTo(event.offsetX, event.offsetY);
ctx.stroke();
}
ctx.beginPath();
ctx.moveTo(event.offsetX, event.offsetY);
}
그럼 오류 수정이 되고 잘 돌아간다 :)
전체 JavaScript
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
const lineWidth = document.querySelector("#line-width");
canvas.width = 700;
canvas.height = 700;
ctx.lineWidth = lineWidth.value;
let isPainting = false;
function onMove(event) {
// 만약에 눌렸다면 그려주세요.
if (isPainting) {
ctx.lineTo(event.offsetX, event.offsetY);
ctx.stroke();
}
ctx.moveTo(event.offsetX, event.offsetY);
}
function onMouseDown() {
//클릭이 됐다는 신호
isPainting = true;
}
function onMouseUp() {
//클릭이 떨어졌다는 신호
isPainting = false;
ctx.beginPath();
}
function onLineWidthChange(event) {
ctx.lineWidth = event.target.value;
}
canvas.addEventListener("mousemove", onMove);
canvas.addEventListener("mousedown", onMouseDown);
canvas.addEventListener("mouseup", onMouseUp);
canvas.addEventListener("mouseleave", onMouseUp);
lineWidth.addEventListener("change", onLineWidthChange);