캔버스 요소(canvas element)는 HTML5의 일부로서 2차원 모양과 비트맵 그림의 스크립트 작성이 가능한 동적 렌더링을 허용한다.

  • IE9 이상 지원합니다.
  • HTML5의 canvas는 자바스크립트를 이용해 원하는 2D그래프를 만들 수 있습니다.
  • Raster방식의 드로잉이기 때문에 픽셀 단위로 컨트롤 합니다.
  • 픽셀로만 컨트롤 되기 때문에 화면이 클수록 성능이 떨어집니다.
canvas 기초
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>Canvas</title>
</head>
<body>
   <canvas id="canvas"></canvas>
    
    <script src="../assets2/js/jquery-1.12.4.min.js"></script>
    <script>
    //javascript
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");
    
    //jQuery
    var canvas = $("#canvas").get(0);
    var ctx = canvas.getContext("2d");
    
        
    </script>
</body>
</html>
Property Description
lineWidth 선의 두께를 설정합니다.
lineCap butt 선의 끝의 모양이 사각협니다.
round 선의 모양이 동그랗습니다.
square 선의 모양이 사각형이빈다. 선 두께 만큼 늘어납니다.
lineJoin round 모서리 모양을 원 모양으로 만듭니다.
bael 모서리 모양을 세모 모양으로 만듭니다.
meter 모서리 모양을 마름모 모양으로 만듭니다.
miterLimit 두 선이 만났을 때 두께를 설정합니다.
getLineDash() 선의 패턴을 설정합니다.
setLineDash() 현재 선의 패턴을 설정합니다.
lineDashOffset() 선의 배열을 어디서 시작할지 설정합니다.
html
라인그리기(lineWidth) View
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>Canvas</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        #canvas {
            border: 1px solid #000;
        }
    </style>
</head>

<body>
    <canvas id="canvas"></canvas>

    <script src="../assets2/js/jquery-1.12.4.min.js"></script>
    <script>
        //javascript
        var canvas = document.getElementById("canvas");
        var ctx = canvas.getContext("2d");
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
        //    var $("#canvas") = $(window).innerWidth    :jquery경우

        //라인 그리기 1
        ctx.beginPath();
        ctx.moveTo(50, 50);
        ctx.lineTo(50, 140);
        ctx.stroke();
        
        //라인 그리기 2
        ctx.beginPath();
        ctx.moveTo(70, 50);
        ctx.lineTo(70, 140);
        ctx.stroke();
        

        //선 10개 그리기
        for (var i = 0; i < 10; i++) {
            ctx.beginPath();
            ctx.moveTo(50+i*20, 150);
            ctx.lineTo(50+i*20, 240);
            ctx.stroke();
        }
        
        //선 라인 두께를 다르게 하기
        
        for (var i = 0; i < 10; i++) {
            ctx.lineWidth = 1 + i;
            ctx.beginPath();
            ctx.moveTo(50+i*20, 250);
            ctx.lineTo(50+i*20, 350);
            ctx.stroke();
        }
        
        //+ 그리기
        ctx.lineWidth = 1
        ctx.beginPath();
        ctx.moveTo(100, 350);
        ctx.lineTo(100, 450);
        ctx.stroke();
        
        ctx.beginPath();
        ctx.moveTo(50, 400);
        ctx.lineTo(150, 400);
        ctx.stroke();
        
        
    </script>
</body>
</html>
라인 모양 설정하기(lineCap) View
<!DOCTYPE html>
<html lang="ko">

<head>
    <meta charset="UTF-8">
    <title>Canvas</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        #canvas {
            border: 1px solid #000;
        }

    </style>
</head>

<body>
    <canvas id="canvas"></canvas>

    <script src="../assets2/js/jquery-1.12.4.min.js"></script>
    <script>
        var canvas = document.getElementById("canvas");
        var ctx = canvas.getContext("2d");
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
        
        ctx.beginPath();
        ctx.moveTo(50,50);
        ctx.lineTo(50,150);
        ctx.lineCap = "butt";
        ctx.lineWidth = 15;
        ctx.stroke();
        
        ctx.beginPath();
        ctx.moveTo(100,50);
        ctx.lineTo(100,150);
        ctx.lineCap = "round";
        ctx.lineWidth = 15;
        ctx.stroke();
        
        ctx.beginPath();
        ctx.moveTo(150,50);
        ctx.lineTo(150,150);
        ctx.lineCap = "square";
        ctx.lineWidth = 15;
        ctx.stroke();
        
        function draw(){
            var lineCap = ['butt','round','squere'];
            
            //안내선
            ctx.strokeStyle = "#09f";
            ctx.lineWidth = 1;
            ctx.beginPath();
            ctx.moveTo(40,200);
            ctx.lineTo(160,200);
            ctx.moveTo(40,300);
            ctx.lineTo(160,300);
            ctx.stroke();
            
            for(var i=0; i<lineCap.length; i++){
                ctx.beginPath();
                ctx.lineWidth = 15;
                ctx.lineCap = lineCap[i];
                ctx.strokeStyle = "#000";
                ctx.moveTo(50+i*50,200);
                ctx.lineTo(50+i*50,300);
                ctx.stroke();
                
            }
        }
        
        draw();

    </script>
</body>

</html>
라인 연결 모양 설정하기(lineJoin) View
<!DOCTYPE html>
<html lang="ko">

<head>
    <meta charset="UTF-8">
    <title>Canvas</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        #canvas {
            border: 1px solid #000;
        }

    </style>
</head>

<body>
    <canvas id="canvas"></canvas>

    <script src="../assets2/js/jquery-1.12.4.min.js"></script>
    <script>
        var canvas = document.getElementById("canvas");
        var ctx = canvas.getContext("2d");
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
        
       function draw(){
           var lineJoin = ['round', 'bevel', 'miter'];
           ctx.lineWidth = 15;
           
           
           for(var i =0; i<lineJoin.length; i++){
               ctx.lineJoin = lineJoin[i];
               ctx.beginPath();
               ctx.moveTo(-5, 5 +i * 40);
               ctx.lineTo(100, 100 +i * 40);
               ctx.lineTo(195, 5 +i * 40);
               ctx.lineTo(290, 100 +i * 40);
               ctx.lineTo(385, 5 +i * 40);
               ctx.stroke();
               
           }
       };
        
        draw();

    </script>
</body>

</html>
대시 라인 설정하기(lineDash) View
<!DOCTYPE html>
<html lang="ko">

<head>
    <meta charset="UTF-8">
    <title>Canvas</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        #canvas {
            border: 1px solid #000;
        }

    </style>
</head>

<body>
    <canvas id="canvas"></canvas>

    <script src="../assets2/js/jquery-1.12.4.min.js"></script>
    <script>
        var canvas = document.getElementById("canvas");
        var ctx = canvas.getContext("2d");
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
        
        
        ctx.lineWidth = 10;
        ctx.beginPath();
        ctx.moveTo(100,50);
        ctx.lineTo(300,50);
        ctx.lineTo(300,100);
        ctx.setLineDash([20]);
        ctx.stroke();
        
        ctx.lineWidth = 10;
        ctx.beginPath();
        ctx.moveTo(100,150);
        ctx.lineTo(300,150);
        ctx.lineTo(300,200);
        ctx.setLineDash([20,10]);
        ctx.stroke();
        
        ctx.lineWidth = 10;
        ctx.beginPath();
        ctx.moveTo(100,250);
        ctx.lineTo(300,250);
        ctx.lineTo(300,300);
        ctx.setLineDash([20,10,50,10]);
        ctx.stroke();
        
        


    </script>
</body>

</html>
대시 라인 움직이기(lineDash) View
<!DOCTYPE html>
<html lang="ko">

<head>
    <meta charset="UTF-8">
    <title>Canvas</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        #canvas {
            border: 1px solid #000;
        }

    </style>
</head>

<body>
    <canvas id="canvas"></canvas>

    <script src="../assets2/js/jquery-1.12.4.min.js"></script>
    <script>
        var canvas = document.getElementById("canvas");
        var ctx = canvas.getContext("2d");
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
        
        var offset = 0;
        
        function draw(){
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            ctx.lineWidth = 1;
            ctx.beginPath();
            ctx.moveTo(100, 100);
            ctx.lineTo(500,100);
            ctx.lineTo(500,500);
            ctx.lineTo(100,500);
            ctx.lineTo(100,100);
            ctx.setLineDash([4,2]);
            ctx.lineDashOffset = -offset;
            ctx.stroke();
        };
        
        function march(){
            offset++;
            
            if(offset > 16){
                offset = 0;
            }
            
            setTimeout(march, 20);
            
            draw();
        };
        
        march()

    </script>
</body>

</html>
Property Description
fillRect(x, y, width, height) 색칠된 직사각형을 그립니다.
strokeRect(x, y, width, height) 색칠된 직사각형을 그립니다.
clearRect(x, y, width, height) 직사각형을 지웁니다. 지워진 부분은 투명해집니다.
사각형 그리기 View

context.strokeRect(x, y, width, height)
  x : 시작하는 점의 x좌표
  y : 시작한는 점의 y좌표
  width : 사각형의 가로 값
  height : 사각형의 세로 값

<!DOCTYPE html>
<html lang="ko">

<head>
    <meta charset="UTF-8">
    <title>Canvas</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        #canvas {
            border: 1px solid #000;
        }

    </style>
</head>

<body>
    <canvas id="canvas"></canvas>

    <script src="../assets2/js/jquery-1.12.4.min.js"></script>
    <script>
        var canvas = document.getElementById("canvas");
        var ctx = canvas.getContext("2d");
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
        
        ctx.strokeRect(50,50,100,100);
        ctx.fillStyle = "pink";
        ctx.fillRect(200,50,100,100);
        
        ctx.fillRect(350,50,100,100);
        ctx.clearRect(375,75,50,50);
        
       

    </script>
</body>

</html>
Property Description
arc(x, y, r, sAngle, eAngle, counterClockwise) 원을 그립니다.
arcTo(x1, y1, x2, y2, r) 원과 호를 연결하여 라운드 코너를 그립니다.
quadraticCurve(cpx, cpy, x, y) 조절점의 커브 라운드를 그립니다.
bezierCurve(cp1x, cp1y, cp2x, cp2y, x, y) 두 조절점의 커브 라운드를 그립니다.
원 그리기 View

context.arc(x, y, r, sAngle, eAngle, counterClockwise
  x : x좌표
  y : y좌표
  r : 원의 반지름
  sAngle : 시작하는 각도
  eAngle : 끝나는 각도
  counterClockwise : 시계방향으로 회전

<!DOCTYPE html>
<html lang="ko">

<head>
    <meta charset="UTF-8">
    <title>Canvas</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        #canvas {
            border: 1px solid #000;
        }

    </style>
</head>

<body>
    <canvas id="canvas"></canvas>
    <script>
        var canvas = document.getElementById("canvas");
        var ctx = canvas.getContext("2d");
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
        
        ctx.arc(150,150,100,0, Math.PI*2);
        ctx.strokeStyle='pink';
        ctx.stroke();
        ctx.fillStyle = 'pink';
        ctx.fill();
        
        ctx.beginPath();
        ctx.moveTo(50,50);
        ctx.lineTo(300,50);
        ctx.arcTo(350,50,350,100, 50);
        ctx.lineTo(350,200);
        ctx.strokeStyle='purple';
        ctx.stroke();
      

    </script>
</body>

</html>
Property Description
beginPath() 새로운 경로를 만듭니다.
closePath() 현재 하위 경로의 시작 부분과 연결된 직선을 추가합니다.
stroke() 선을 그립니다.
fill() 내부가 채워진 도형을 그립니다.
moveTo(x, y) x, y의 지정된 좌표로 옮깁니다.
lineTo(x, y) x, y의 지정된 좌표로 선을 그립니다.
패스 그리기 View
<!DOCTYPE html>
<html lang="ko">

<head>
    <meta charset="UTF-8">
    <title>Canvas</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        #canvas {
            border: 1px solid #000;
        }

    </style>
</head>

<body>
    <canvas id="canvas"></canvas>
    <script>
        var canvas = document.getElementById("canvas");
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;

        //        ctx.beginPath();
        //        ctx.moveTo(75,50);
        //        ctx.lineTo(100,75);
        //        ctx.lineTo(100,25);
        //        ctx.fill();

        if (canvas.getContext) {
            var ctx = canvas.getContext("2d");
            ctx.beginPath();
            ctx.arc(75, 75, 50, 0, Math.PI*2, true);
            ctx.moveTo(110, 75);
            ctx.arc(75,75,35,0,  Math.PI, false);
            ctx.moveTo(65,65);
            ctx.arc(60, 65, 5, 0, Math.PI*2, true);
            ctx.moveTo(95,65);
            ctx.arc(90, 65, 5, 0, Math.PI*2, true);
            
            
            ctx.stroke();

    </script>
</body>

</html>
사각형 움직이기 View
<!DOCTYPE html>
<html lang="ko">

<head>
    <meta charset="UTF-8">
    <title>Canvas</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        #canvas {
            border: 1px solid #000;
        }

    </style>
</head>

<body>
    <canvas id="canvas"></canvas>
    <script>
        var canvas = document.getElementById("canvas");
        var ctx = canvas.getContext("2d");
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;

        var ctxW = canvas.width;
        var ctxY = canvas.height;
        var x = 0;
        
        function animation(){
            ctx.clearRect(0,0,ctxW,ctxY);
            ctx.fillStyle = "pink";
            ctx.fillRect(x, 10, 50, 50);
            x+=10;
        }
        
        setInterval(animation, 30);

    </script>
</body>

</html>
클릭하면 움직임 정지하기View
<!DOCTYPE html>
<html lang="ko">

<head>
    <meta charset="UTF-8">
    <title>Canvas</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        #canvas {
            border: 1px solid #000;
        }

    </style>
</head>

<body>
    <canvas id="canvas"></canvas>
    <script>
        var canvas = document.getElementById("canvas");
        var ctx = canvas.getContext("2d");
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;

        var ctxW = canvas.width;
        var ctxY = canvas.height;
        var x = 0;
        var y = 0;
        
        
        function animate(){
            ctx.clearRect(0,0,ctxW, ctxY);
            ctx.fillStyle ="pink";
            ctx.fillRect(x,10,50,50);
            ctx.fillStyle ="beige";
            ctx.fillRect(10,y,50,50);
            x++;
            y++;
            
        }
        
        //영역 제한
        
        if(x > ctxW){
            x = 0;
        }
        
        if(y > ctxW){
            y = 0;
        }
        
        var animateInterval = setInterval(animate, 30);
        
        $("#canvas").click(function(){
            clearInterval(animateInterval);
        });
        

    </script>
</body>

</html>
클릭하면 사격형 만들기View
<!DOCTYPE html>
<html lang="ko">

<head>
    <meta charset="UTF-8">
    <title>Canvas</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        #canvas {
            border: 1px solid #000;
        }

    </style>
</head>

<body>
    <canvas id="canvas"></canvas>
    <script>
        var canvas = document.getElementById("canvas");
        var ctx = canvas.getContext("2d");
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
        
        $("#canvas").click(function(){
            var mouseX = event.clientX;
            var mouseY = event.clientY;
            ctx.fillStyle="pink";
            ctx.fillRect(mouseX -10,mouseY -10,20,20);
        });
        

    </script>
</body>

</html>
눈내리는 이미지 만들기View
<!DOCTYPE html>
<html lang="ko">

<head>
    <meta charset="UTF-8">
    <title>Canvas</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        #canvas {
            border: 1px solid #000;
        }

    </style>
</head>

<body>
    <canvas id="canvas"></canvas>
    <script>
        var canvas = document.getElementById("canvas");
        var ctx = canvas.getContext("2d");

        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;

        var ctxW = ctx.canvas.width +100;
        var ctxH = ctx.canvas.height +100;



        var snowflakes = [];
        var tatalCount = 10;

        var bgImage = new Image();
        bgImage.src = "img/bg.jpg";

        //눈송이를 추가

        function addsnowflakes() {
            if (snowflakes >= tatalCount) {
                return;
            }

            //x의 좌표값을 랜덤으로 저장
            var x = Math.floor(Math.random() * ctxW) - 100;
            var y = 0;
            //눈송이의 크기를 랜덤으로 저장
            var size = Math.floor(Math.random() * 3) + 1;
            
            snowflakes.push({ "x":x, "y":y, "size":size})
        }


        //눈송이
        function snow() {
            addsnowflakes();
            
            ctx.fillStyle = "rgba(255,255,255,0.75)";
            
            for(var i in snowflakes){
                ctx.beginPath();
                var ty= snowflakes[i].y += snowflakes[i].size * 0.5;
                ctx.arc(snowflakes[i].x, snowflakes[i].y++, snowflakes[i].size, 0, Math.PI * 2);
                ctx.fill();
            }
            
            if(snowflakes[i].y > ctxH){
                snowflakes.splice(i,1);
            }
        };
        
        
        
        //눈송이 개수
        function displayCount(){
            ctx.fillStyle = "white";
            ctx.font = "bold 14px Arial, sans-serif";
            ctx.fillText(snowflakes.length, 10, 20);
        };

        function animate() {
            ctx.save();
            ctx.clearRect(0, 0, ctxW, ctxH);
            //            ctx.drawImage(bgImage,0,0);
            
            displayCount();
            ctx.rotate(-0.2);
            snow();
            ctx.restore();
        };

        var animateInterval = setInterval(animate, 30);
    </script>
</body>

</html>
우주 이미지 만들기View(방향키: A(좌),D(우))
<!DOCTYPE html>
<html lang="ko">

<head>
    <meta charset="UTF-8">
    <title>Canvas</title>
    <style>
        * {margin: 0;padding: 0;}
        #canvas {background: url(img/space2.jpg); -webkit-background-size: cover;
        background-size: cover; }

    </style>
</head>

<body>
    <canvas id="canvas"></canvas>
    
    
    <script src="../assets2/js/jquery-1.12.4.min.js"></script>
    <script>
        var canvas = document.getElementById("canvas");
        var ctx = canvas.getContext("2d");
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
        var canW = canvas.width;
        var canH = canvas.height;
        var speed = 20;
        var keyCodeValue;
        var keysDown = {};
        
        //비행기 이미지
        var fighterImage = new Image();
        fighterImage.src = "img/rocket2.png";

        function Player(){
            this.x = canW * 0.5 - 50,
            this.y = 500,
            this.w = 100,
            this.h = 170;
            this.missiles = [];
            this.render = function() {
                ctx.strokeStyle = "rgba(255,255,255,0)";
                ctx.strokeRect(this.x, this.y, this.w, this.h);
                ctx.drawImage(fighterImage, this.x, this.y);
                
                //미사일 발사
                for(var i=0; i<this.missiles.length; i++){
                    var m = this.missiles[i];
                    ctx.fillStyle = m.bg;
                    ctx.fillRect(m.x, m.y -= 10, m.w, m.h);
                    
                    //화면 밖의 미사일은 삭제
                    
                    if(m.y <=0){
                        this.missiles.splice(i,1);
                    }
                }
            }
        }
        
        function update(){
            if(65 in keysDown){
                player.x -= speed;
            } else if(68 in keysDown){
                player.x += speed
            } 
            
            //limit
            if(player.x < 0){
                player.x = 0;
            } else if(player.x > (canW - player.w)){
                player.x = canW - player.w;
            } else if(player.y  < 0){
                player.y = 0;
            } else if(player.y > (canH - player.h)){
                player.y = canH - player.h;
            }
        }
        
        //키보드 클릭
        $(document).keydown(function(event){
            keysDown[event.keyCode] = true;
            
            //스페이스 바
            if(event.keyCode === 32){
                player.missiles.push({"x" : player.x + player.w-25, "y":player.y -5,
                                     "w":5, "h":10, "bg":"yellow"})
                player.missiles.push({"x" : player.x + player.w-75, "y":player.y -5,
                                     "w":5, "h":10, "bg":"yellow"})
                player.missiles.push({"x" : player.x + player.w-50, "y":player.y -5,
                                     "w":5, "h":10, "bg":"yellow"})
            }
        });
        
        //키보드 해제
        $(document).keyup(function(event){
            delete keysDown[event.keyCode];
        });
        
        

        var player = new Player();

        function animate(){
            ctx.clearRect(0,0,canW,canH);
            update();
            player.render();
        }
        
        
        setInterval(animate, 30);
  
        
       

    </script>
</body>

</html>