2022 SW 전문인재양성사업/웹 프로그래밍 기본
canvas (2) - 선 그리기
마루설아
2022. 7. 29. 12:06
<!DOCTYPE html>
<html lang="en">
<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>
<style>
canvas#myCanvas{
border: 1px solid blue;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="640" height="480"></canvas>
<script>
var canvas = document.querySelector("#myCanvas");
var ctx = canvas.getContext("2d");
var drawing = false;
ctx.lineStyle = "black";
ctx.lineWidth = 2;
ctx.beginPath();
canvas.addEventListener('mousedown', (e) => {
drawing = true;
ctx.moveTo(e.pageX, e.pageY);
})
canvas.addEventListener('mouseup', (e) => {
drawing = false;
})
canvas.addEventListener('mousemove', (e) => {
if(drawing){
ctx.lineTo(e.offsetX, e.offsetY);
ctx.stroke();
};
})
</script>
</body>
</html>