Computer >> 컴퓨터 >  >> 프로그램 작성 >> HTML

HTML5 Canvas로 패턴 만들기


HTML5 Canvas로 패턴을 생성하려면 다음 방법을 사용하십시오:createPattern(image, repeat)- 이 방법은 이미지를 사용하여 패턴을 생성합니다. 두 번째 인수는 repeat, repeat-x, repeat-y 및 no-repeat 값 중 하나가 있는 문자열일 수 있습니다. 빈 문자열이나 null이 지정되면 반복이 가정됩니다.

예시

다음 코드를 실행하여 패턴을 만드는 방법을 배울 수 있습니다 -

<!DOCTYPE HTML>
<html>
   <head>
      <style>
         #test {
            width:100px;
            height:100px;
            margin: 0px auto;
         }
      </style>
      <script>
         function drawShape(){
            // get the canvas element using the DOM
            var canvas = document.getElementById('mycanvas');
           
            // Make sure we don't execute when canvas isn't supported
            if (canvas.getContext){
               // use getContext to use the canvas for drawing
               var ctx = canvas.getContext('2d');
               
               // create new image object to use as pattern
               var img = new Image();
               img.src = 'images/pattern.jpg';
               img.onload = function(){
                  // create pattern
                  var ptrn = ctx.createPattern(img,'repeat');
                  ctx.fillStyle = ptrn;
                  ctx.fillRect(0,0,150,150);
               }
            } else {
               alert('You need Safari or Firefox 1.5+ to see this demo.');
            }
         }
      </script>
   </head>
   <body id = "test" onload = "drawShape();">
      <canvas id = "mycanvas"></canvas>
   </body>
</html>