jQuery | javascript | CSS

HTML5 - 10.canvas : 마우스로 그리기

Godffs 2014. 2. 16. 16:55
반응형
마우스 이벤트 중에서
mousedown 상태에서 마우스를 이동하 mouserup 할 때 선을 그리는 예제 입니다.

ex07.sketch.html
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <canvas id="can1" width="500" height="500" style="background-color:yellow;" ></canvas>
    <script type="text/javascript">
        var canvas = document.getElementById("can1");
        var cv = canvas.getContext("2d");
 
        canvas.onmousedown = function (event) {
            var x = event.x;
            var y = event.y;
            
            cv.beginPath();
 
            cv.moveTo(x, y);
            cv.stroke();
            cv.lineWidth = 3;;
        }
 
        canvas.onmouseup = function (event) {
            var x = event.x;
            var y = event.y;
 
            cv.lineTo(x, y);
            cv.stroke();
            cv.lineWidth = 3;
 
            cv.closePath();
        }
    </script>
</body>
</html>
 

결과를 확인합니다. (아래 실제 테스트 가능하도록 했습니다.)
티스토리에 넣으니깐 위치가 이상하네요...;;;


참 쉽죠~? 끝
반응형