>  기사  >  웹 프론트엔드  >  HTML5 프로그래밍 실습 2부 - 애니메이션을 사용하여 그림 코드 케이스 전환

HTML5 프로그래밍 실습 2부 - 애니메이션을 사용하여 그림 코드 케이스 전환

黄舟
黄舟원래의
2017-03-30 13:30:211712검색

이 글에 사용된 주요 지식

이 글은 주로 CanvasAPI의 drawImage 메소드를 아래에 간략하게 소개합니다.

drawImage 메소드는 Canvas API에서 이미지를 그리는 데 사용되는

오버로드된 메소드입니다.

context.drawImage(image,x,y);
context.drawImage(image,x,y,w,h);
context.drawImage(image,sx,sy,sw,sh,dx,dy,dw,dh);

첫 번째 메소드에는 세 개의 매개변수가 있습니다. 첫 번째 매개변수는 그릴 이미지(비디오 요소일 수도 있음)이고 x와 y는 이미지의 시작 좌표입니다.

두 번째 방법에는 5개의 매개변수가 있습니다. 처음 세 개는 첫 번째 방법과 같은 의미입니다. w와 h는 그림을 그릴 때 이미지의 너비와 높이를 나타내며 이미지를 확대/축소하는 데 사용할 수 있습니다. > 세 번째 방법에는 9개의 매개변수가 있습니다. 첫 번째 매개변수는 처음 두 가지 방법과 동일한 의미를 가지며, 마지막 8개 매개변수 중 처음 4개는 소스 이미지에 직사각형을 지정하는 데 사용됩니다. 전체 메소드의 기능은 소스 이미지의 일부(두 번째에서 다섯 번째 매개변수로 정의된 부분)를 캔버스(마지막 네 매개변수로 정의된 부분)에 복사하는 것입니다. 세 번째. 그리기를 완료하는 방법

소스 코드

<!DOCTYPE html><html><head>
    <meta charset="UTF-8">
    <title>用动画的形式切换图片</title>
    <script type="text/javascript">
        var width, height;        
        var context, image, functionId;        
        var drawLeft, drawWidth;        
        var drawTop, drawHeight;        
        var spaceWidth, spaceHeight;        
        var speed=5000;        
        var images = ["http://i.6.cn/cvbnm/4e/7e/bb/75f251a8e2ae935d598f17b4f8275060.jpg", 
        "http://i.6.cn/cvbnm/4a/6e/fb/805175016e502c483b75276f29801df3.jpg", 
        "http://i.6.cn/cvbnm/6a/72/18/1787a3b2754ef48e374bbd14635f5c36.jpg", 
        "http://i.6.cn/cvbnm/94/55/6c/b1ba743ba617be2891fa06b67d795511.jpg", 
        "http://i.6.cn/cvbnm/02/1b/04/8018ee9e5756ac6b30f27d7ad6396b03.jpg", 
        "http://i.6.cn/cvbnm/85/ea/d1/65f15857b971afb3b6e38b5fcdadc9c0.jpg"];        
        function selectFrom(iFirstValue, iLastValue) {            
        var iChoices = iLastValue - iFirstValue + 1;            
        return Math.floor(Math.random() * iChoices + iFirstValue);
        }        function showPicture(effects) {            
        var count = 0;            
        for (var o in effects) {
                count++;
            }           
             var canvas = document.getElementById(&#39;canvas&#39;);
            context = canvas.getContext(&#39;2d&#39;);
            width = canvas.width;
            height = canvas.height;            
            var currImage = 0;
            image = new Image();
            image.src = images[currImage];
            context.drawImage(image, 0, 0, width, height);
            currImage++;            
            if (count > 0) {
                setInterval(function () {                    
                var rand =  selectFrom(0, count - 1);
                    image.src = images[currImage];
                    currImage++;                    
                    if (currImage == images.length) {
                        currImage = 0;
                    }                    
                    var index = 0;                    
                    for (var effect in effects) {                        
                    if (index++ == rand) {
                            effects[effect]();                            
                            break;
                        }
                    }
                }, speed);
            }
        }

        window.onload=function(){
            showPicture({
                leftToRight: function () {
                    context.fillStyle = "#EEEEFF";
                    context.fillRect(0, 0, width, height);
                    drawWidth = 0;
                    functionId = self.setInterval("drawleftToRight()", 10);
                },
                topToBottom: function () {
                    context.fillStyle = "#EEEEFF";
                    context.fillRect(0, 0, width, height);
                    drawHeight = 0;
                    functionId = self.setInterval("drawtopToBottom()", 10);
                },
                hcenter: function () {
                    context.fillStyle = "#EEEEFF";
                    context.fillRect(0, 0, width, height);
                    drawLeft = width / 2;
                    drawWidth = 0;
                    functionId = self.setInterval("drawhcenter()", 10);
                },
                vcenter: function () {
                    context.fillStyle = "#EEEEFF";
                    context.fillRect(0, 0, width, height);
                    drawTop = height / 2;
                    drawHeight = 0;
                    functionId = self.setInterval("drawvcenter()", 10);
                },
                hwindow: function () {
                    context.fillStyle = "#EEEEFF";
                    context.fillRect(0, 0, width, height);
                    spaceWidth = width / 10;
                    drawWidth = 0;
                    functionId = self.setInterval("drawhwindow()", 50);
                },
                vwindow: function () {
                    context.fillStyle = "#EEEEFF";
                    context.fillRect(0, 0, width, height);
                    spaceHeight = height / 10;
                    drawHeight = 0;
                    functionId = self.setInterval("drawvwindow()", 50);
                },
                hvwindow: function () {
                    context.fillStyle = "#EEEEFF";
                    context.fillRect(0, 0, width, height);
                    spaceHeight = height / 10;
                    spaceWidth = width / 10;
                    drawWidth = 0;
                    drawHeight = 0;
                    functionId = self.setInterval("drawhvwindow()", 50);
                }
            });
        }        function drawleftToRight() {
            context.drawImage(image, 0, 0, drawWidth, image.height, 0, 0, drawWidth, image.height);
            drawWidth = drawWidth + 2;            
            if (drawWidth > width) {
                window.clearInterval(functionId);
            }
        }        function drawtopToBottom() {
            context.save();
            context.drawImage(image, 0, 0, image.width, drawHeight, 0, 0, image.width, drawHeight);
            drawHeight = drawHeight + 2;            
            if (drawHeight > height) {
                window.clearInterval(functionId);
            }
            context.restore();
        }        
        function drawhcenter() {
            context.save();
            context.drawImage(image, drawLeft, 0, drawWidth, image.height, drawLeft, 0, drawWidth, image.height);
            drawLeft = drawLeft - 1;
            drawWidth = drawWidth + 2;            
            if (drawLeft <= 0) {
                window.clearInterval(functionId);
            }
            context.restore();
        }        
        function drawvcenter() {
            context.save();
            context.drawImage(image, 0, drawTop, image.width, drawHeight, 0, drawTop, image.width, drawHeight);
            drawTop = drawTop - 1;
            drawHeight = drawHeight + 2;            
            if (drawTop <= 0) {
                window.clearInterval(functionId);
            }
            context.restore();
        }        function drawhwindow() {            
        for (i = 0; i < 10; i++) {
                context.drawImage(image, 0 + i * spaceWidth, 0, drawWidth, 
                image.height, 0 + i * spaceWidth, 0, drawWidth, image.height);
            }
            drawWidth += 1;            
            if (drawWidth - 1 > spaceWidth) {
                window.clearInterval(functionId);
            }
        }        function drawvwindow() {
            context.save();
            context.clearRect(0, 0, width, height);            
            for (i = 0; i < 10; i++) {
                context.drawImage(image, 0, 0 + i * spaceHeight, image.width, 
                drawHeight, 0, 0 + i * spaceHeight, image.width, drawHeight);
            }
            drawHeight += 1;            
            if (drawHeight - 1 > spaceHeight) {
                window.clearInterval(functionId);
            }
            context.restore();
        }        function drawhvwindow() {
            context.save();
            context.clearRect(0, 0, width, height);            
            for (i = 0; i < 10; i++) {                
            for (j = 0; j < 10; j++) {
                    context.drawImage(image, 0 + j * spaceWidth, 0 + i * 
                    spaceHeight, drawWidth, drawHeight, 0 + j * spaceWidth, 0 + i * 
                    spaceHeight, drawWidth, drawHeight);
                }
            }
            drawHeight += height / width;
            drawWidth += 1;            
            if (drawHeight > spaceHeight) {
                context.drawImage(image, 0, 0, width, height);
                window.clearInterval(functionId);
            }
            context.restore();
        }    </script></head><body>
    <h1>用动画的形式切换图片</h1>
    <canvas id="canvas" width="192px" height="255px"></canvas></body></html>

코드 분석

 drawleftToRight(): 효과는 왼쪽에서 오른쪽으로 표시되는 것입니다. 4번째 매개변수와 4번째 매개변수는 0에서 그림의 너비에 따라 점차적으로 증가합니다.

drawtopToBottom(): 효과는 위에서 아래로 표시되며, 주로 5번째와 9번째 매개변수를 0에서 9번째로 증가시킵니다. 그림의 높이

 drawhcenter(): 가운데에서 양쪽으로 가로로 표시하는 효과입니다. 주로 두 번째와 여섯 번째 매개변수를 이미지 너비의 절반에서 0으로 줄이고, 네 번째와 여덟 번째 매개변수를 줄입니다. 0에서 이미지 너비로 증가

drawvcenter(): 효과는 이전과 유사하게 중앙에서 양쪽, 위아래로 표시하는 것입니다.

drawhwindow(): 효과 수평 블라인드입니다. drawhcenter 방법의 원리와 비슷하지만 여기 여러 곳에서 수행된다는 점이 다릅니다.

drawvwindow(): 효과는 수직 블라인드이며 원리는 drawvcenter 방법과 유사합니다. 여기 여러 곳에서 수행되었습니다

drawhvwindow(): 효과는 블라인드입니다. drawhwindow() drawvwindow()와의 조합

추가하고 개선하는 모든 분들을 환영합니다

그림 이후 다른 웹사이트에 게재되어 있는 경우 로딩이 느리고 원활하지 않습니다. 이

지도

를 사용하면 더 나은 효과를 얻을 수 있습니다.

위 내용은 HTML5 프로그래밍 실습 2부 - 애니메이션을 사용하여 그림 코드 케이스 전환의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.