라라리라

2023.11.02 / Step 8 [DOM_canvasMouse] - 코딩 82 일차 본문

코딩/2023 JavaScript DOM

2023.11.02 / Step 8 [DOM_canvasMouse] - 코딩 82 일차

헤실 2023. 11. 2. 17:47

clickDrawArc.html

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <canvas id="myCanvas" width="800" height="600" style="border: 1px solid black;">
    </canvas>
    <h1>화면을 클릭해보세요.</h1>
    <script src="clickDrawArc.js"></script>
</body>
</html>

 


clickDrawArc.js

 

function drawArc(){
    ctx.beginPath();

    ctx.arc(x, y, radius, 0, angle);
    ctx.fillStyle = "blue";
    ctx.fill();

    ctx.closePath();
}

//-------------------------------------------------
let canvas = document.getElementById("myCanvas");
let ctx = canvas.getContext("2d");
console.log("캔버스 왼쪽 여백 = " + ctx.canvas.offsetLeft);
console.log("캔버스 상단 여백 = " + ctx.canvas.offsetTop);

let x = 0;
let y = 0;
let radius = 40;
let angle = Math.PI * 2;


window.addEventListener('click', (event) => {
    //캔버스의 시작위치는  모니터의 시작위치와 다르다.
    //그간격만큼 조정한다.
   
    x = event.offsetX
    y = event.offsetY

    console.log(event.clientX , ctx.canvas.offsetLeft , x);
    console.log(event.clientY , ctx.canvas.offsetTop , y);
    drawArc();
});
 

 


clicktest과제.html

 

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <canvas id="myCanvas" width=" 800px" height="800px" style="border: 1px solid black;"></canvas>
    <script src="clicktest과제.js"></script>
</body>
</html>

 

 


clicktest과제.js

 

function drawcircle(){
    cnt.beginPath();
    cnt.rect(x, y, 30, 30);
    cnt.fillStyle = "yellow"
    cnt.fill();
    cnt.stroke();
    cnt.closePath();
}
let myCanvas = document.querySelector("#myCanvas");
let cnt = myCanvas.getContext("2d");
let x = 0;
let y = 0;
window.addEventListener("mousedown" ,(a)=>{
    x = a.offsetX;
    y = a.offsetY;
    drawcircle();
})