iT邦幫忙

0

【Canvas & JS】在畫圖之前已alert()圖卻仍畫出(或沒消除)

各位大大好,這段程式碼是寫一個球往上移動的簡單動畫,每一個Frame要作的事依序是:
清除前格的圖像→If判斷→畫新的位置的球
If判斷那邊寫了一個alert()
照理來說當alert的警示跳出時,前格的圖像已清除,緊接著的球還沒畫,這時畫面上應該沒有任何球才是,但是實際上卻有,找不到原因,懇請各位大大指教,感恩!

PS:程式碼中的console.log是為了方便查看上述三步驟的執行狀況

codepen:https://codepen.io/hkk2018/pen/oPNzzo
codepen的console欄跟chrome的表現有點不一樣(略怪異),建議下面的程式碼直接複製到html的body測試比較好。

    <style>
        body {
            margin: 0;
        }

        canvas {
            background: #eee;
            display: block;
            margin: auto;
        }
    </style>
    <canvas id="myCanvas" width="480" height="320"></canvas>
    <script>
        setInterval(draw, 700);

        let canvas = document.getElementById("myCanvas");
        let ctx = canvas.getContext("2d");

        let y = canvas.height - 30;
        let ballRadius = 10;
        let dy = -7;

        let frameCount = 0;

        function draw() {
            frameCount++;
            console.log("Now the frame is", frameCount);
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            console.log("Previous frame is cleaned", frameCount);
            if (frameCount == 10) {
                console.log("alert", frameCount);
                alert("alert");
            }
            y += dy;
            console.log("going to draw ball", frameCount);
            drawBall();
        }

        function drawBall() {
            ctx.beginPath();
            ctx.arc(canvas.width / 2, y, ballRadius, 0, Math.PI * 2);
            ctx.fillStyle = "#0095DD";
            ctx.fill();
            ctx.closePath();
            console.log("drawBall is done", frameCount);
        }

    </script>
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

2
神Q超人
iT邦研究生 5 級 ‧ 2018-08-21 00:48:10
最佳解答

HELLO!
這個問題的原因是因為程式跑太快了XD
他在跑到alert的時候雖然已經執行了ctx.clearRect();
但問題在他還沒清除完canvas的內容,
就已經因為alert跳出來給暫停住執行了,
可以用chrome的開發者工具下中斷點去看,
如果斷在alert之前他會是清除的狀態:
https://ithelp.ithome.com.tw/upload/images/20180821/201069354uwEyGnpy4.jpg

小不釘 iT邦新手 2 級 ‧ 2018-08-21 00:58:41 檢舉

原來如此,受教了
謝謝你,神Q超人!

神Q超人 iT邦研究生 5 級 ‧ 2018-08-21 09:05:42 檢舉

哈哈,不會啦!
我一開始也覺得很神奇XD

我要發表回答

立即登入回答