캔버스 애니메이션 효과 봉인

2313 단어




    demo
    
    
    




    
canvas,
(function() { var canvas = document.querySelector('#canvsElem'); var ctx = canvas.getContext('2d'); canvas.width = 600; canvas.height = 600; canvas.style.border = '1px solid #000'; var s = new Sprite({ x: 200, y: 50, w: 100, h: 100*2, fps: 4, originW: 40, originH: '65', _imgSrc: '123.jpg' }); console.log(s); s.render(ctx); }());

부분
function Sprite( option ) {
    this._init( option );
}

Sprite.prototype = {
    _init: function ( option ) {
        this.x = option.x === 0 ? 0 : ( option.x || 10 );//10
        this.y = option.y === 0 ? 0 : ( option.y || 10 );//10
        
        this.w = option.w || 40; // canvas 
        this.h = option.h || 65;

        this.fps = option.fps || 10 ;//frame per second
        this.originW = option.originW || 40; //   
        this.originH = option.originH || 65;

        this._dirIndex = 0;

        this._imgSrc = option._imgSrc || '';
    },
    render: function (ctx) {//   
        //  :  
        var img = new Image();
        img.src = this._imgSrc;

        var self = this;

        img.onload = function() {
            var frameIndex = 0;
            // this == img
            //  :  ,    , 
            setInterval(function() {
                ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height);
                ctx.drawImage(
                    img // 
                    , frameIndex * self.originW // x 
                    ,self._dirIndex * self.originH
                    ,self.originW
                    ,self.originH
                    ,self.x
                    ,self.y
                    ,self.w
                    ,self.h     
                );

                frameIndex ++;
                frameIndex %= 4;
            }, 1000 / self.fps)
        }
    }
}

좋은 웹페이지 즐겨찾기