javascript異步編程—-用jscex畫圓

今天來畫圓吧!

     在支持html5的瀏覽器中執行下面代碼:

<!DOCTYPE HTML>
<html>
<body>

<canvas id="myCanvas" width="480" height="300" style="border:1px solid #c3c3c3;">
Your browser does not support the canvas element.
</canvas>
<script type="text/javascript">

    var c = document.getElementById("myCanvas");
    var cxt = c.getContext("2d");
    var x = 150;
    var y = 150;
    var r = 100;
    cxt.moveTo(x – r, y);
    for (var i = x – r; i < x + r + 1; i++) {
        var tempY = Math.pow(r * r – (x – i) * (x – i), 1 / 2);
        cxt.lineTo(i, y + tempY);
    }
    cxt.moveTo(x – r, y);
    for (var i = x – r; i < x + r + 1; i++) {
        var tempY = Math.pow(r * r – (x – i) * (x – i), 1 / 2);
        cxt.lineTo(i, y – tempY);
    }
      cxt.stroke();

</script>

</body>
</html>
在Canvas裡顯示如下:

 

但是,我們明明是在畫圓,怎麼沒有看到畫圓的過程?javascript就是這樣,解釋完就畫完瞭,而不會呈現解釋的過程,這也是為什麼javascript不用考慮多線程問題,僅僅UI線程。那麼怎麼看到畫圓的過程?

jscex閃亮登場!

<!DOCTYPE HTML>
<html>
<body>
<canvas id="myCanvas" width="480" height="300" style="border:1px solid #c3c3c3;">
Your browser does not support the canvas element.
</canvas>
    <script language="javascript" type="text/javascript" src="lib/uglifyjs-parser.js"></script>
    <script language="javascript" type="text/javascript" src="src/jscex.js"></script>
    <script language="javascript" type="text/javascript" src="src/jscex.builderBase.js"></script>
    <script language="javascript" type="text/javascript" src="src/jscex.async.js"></script>
<script type="text/javascript">
    var c = document.getElementById("myCanvas");
    var cxt = c.getContext("2d");
    var x = 150;
    var y = 150;
    var r = 100;
    var drawAsync = eval(Jscex.compile("async", function () {
        cxt.moveTo(x – r, y);
        for (var i = x – r; i < x + r + 1; i++) {
            $await(Jscex.Async.sleep(10));
            var tempY = Math.pow(r * r – (x – i) * (x – i), 1 / 2);
            cxt.lineTo(i, y + tempY);
            cxt.stroke();
        }
        cxt.moveTo(x – r, y);
        for (var i = x – r; i < x + r + 1; i++) {
            $await(Jscex.Async.sleep(10));
            var tempY = Math.pow(r * r – (x – i) * (x – i), 1 / 2);
            cxt.lineTo(i, y – tempY);
            cxt.stroke();
        }
     
    }));
    drawAsync().start();
</script>

</body>
</html>
 

 這樣就可以目睹畫圓全過程!

 

發佈留言