소프트웨어 이론교육/웹 프로그래밍 기본

canvas (1) - 기초

마루설아 2022. 7. 29. 11:38
<!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 burlywood;
        }
    </style>
</head>
<body>
    <canvas id="myCanvas" width="640" height="480"></canvas>

    <script>
        var ctx = document.querySelector("#myCanvas").getContext("2d");
        console.log(ctx);

        ctx.fillStyle = "#ff0000";

        var x = 0;
        var int = setInterval(function(){
            x += 10;
            if(x>=500){
                clearInterval(int);
            }
            ctx.fillStyle = "#FFFFFF";
            ctx.fillRect(x-10, 50, 100, 80);
            ctx.fillStyle = "#ff0000";
            ctx.fillRect(x, 50, 100, 80);
        }, 20);

        // 원 그리기
        ctx.strokeStyle = "#00FF00";
        ctx.lineWidth = 5;
        ctx.beginPath();
        ctx.arc(200, 200, 100, 0, 2*Math.PI);
        ctx.stroke();

        // 선 그리기
        ctx.strokeStyle = "#0000FF";
        ctx.lineWidth = 5;
        ctx.beginPath();
        ctx.moveTo(300, 300);
        ctx.lineTo(50, 0);
        ctx.stroke();
    </script>
</body>
</html>