簡體   English   中英

如何使用setInterval和HTML5 Canvas解決無響應的重繪和控件

[英]How to address unresponsive redraws and controls with setInterval and HTML5 Canvas

我目前正在開發一個簡單的HTML5游戲,您可以在以下URL上進行測試:

http://frankcaron.com/simplegame/game.html

代碼在這里:

https://github.com/frankcaron/Personal_HTML5_GamePrototype/blob/master/js/game.js

為了設置元素動畫,我使用了一些setIntervals。 游戲的主循環有一個setInterval可以正常工作。 某些衰落元素也可以使用它們,而不會出現問題。 我遇到的一個問題是點擊動畫。

我遇到的問題是,在Safari中以及在某種程度上在Chrome中,單擊事件和動畫沒有響應。 它不會每次都觸發。 我認為與並發間隔運行有一些沖突。 我不知道為什么。

我已經使用requestAnimFrame對HTML5動畫的另一種方法進行了一些研究,但我認為這不會解決我的問題。

這是感興趣的代碼:

//Track mousedown
addEventListener('mousedown', function (e) {
    //Safari Fix
    e.preventDefault();
    //If you click while the game is going, do your special move
    performSpecial();
}

//Perform a special move
var performSpecial = function () {
    switch(classType)
    {
        case 1:
            //Class 1
            break;
        default:
            //No class
            renderExplosion();
    }
}

//Render explosion special move
var renderExplosion = function () {
    //Temp vars
    var alpha = 1.0;   // full opacity
    var circleMaxRadius = 32;
    fadeCircle = setInterval(function () {
        ctx.beginPath();
        ctx.arc(hero.x + 16, hero.y + 16, circleMaxRadius, 0, 2 * Math.PI, false);
        ctx.lineWidth = 5;
        ctx.strokeStyle = "rgba(255, 0, 0, " + alpha + ")";
        ctx.stroke();
        circleMaxRadius = circleMaxRadius + 5;
        alpha = alpha - 0.05 ; // decrease opacity (fade out)
        if (alpha < 0) {
            clearInterval(fadeCircle);
        }
    }, 1); 
};

抱歉,我使用window.requestAnimationFrame重新編寫了應用程序,而我不再遇到這個問題。 如果有人想查看完整的解決方案,則代碼在我的Github上。

簡而言之,我刪除了所有間隔並替換了整個游戲循環。 當需要動畫效果時,我將與事件對應的標志打開。 渲染器檢查此條件,並在標志打開時渲染效果,完成后再次關閉標志。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM