簡體   English   中英

HTML5畫布錯誤

[英]Html5-canvas Bug

因此,我正在使用<canvas>標記測試我的技能,並決定在一個簡單且CSS稀缺的網頁上制作繪圖功能。 這是我的代碼。

<html>
    <head>
        <script>
function graph(equation){
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    ctx.clearRect(0-c.width/2, 0-c.height/2, c.width, c.height);
    ctx.translate(c.width/2,c.height/2);
    ctx.strokeStyle = "red";
    ctx.moveTo(0-c.width/2,0);
    ctx.beginPath();
    for(i=0-c.width/2;i<=c.width;i++){
        ctx.lineTo(i,eval(equation.replace(/x/g,i.toString()))*-1);
    };
    ctx.stroke()
    ctx.closePath();
}
        </script>
    </head>
    <body>
        <canvas id="myCanvas" width="700" height="550" style="border:1px solid #d3d3d3;">
            Your browser does not support the HTML5 canvas tag.
        </canvas>
        <textarea id="graphi" height="16px" width="200"></textarea>
        <button onclick="graph(document.getElementById('graphi').value);">graph</button>
    </body>
</html>

我的問題是,每當我對其繪制兩次圖形時,它都會更改(0,0)的位置,除非完全重置頁面,否則無法將其更改回去。 所以我的問題確實是我的功能出了什么問題以及如何解決? 提前致謝。

getContext不會創建新的上下文,而是每次都返回相同的上下文。 獲取上下文后,您將其翻譯,並且它將保持翻譯狀態。

要解決此問題,請在功能末尾僅翻譯一次上下文,或在使用后將其翻譯回。

順便說一句,一種不更改上下文幾何結構(平移,旋轉,縮放)的簡單方法是在函數的開頭使用context#save並在函數的末尾使用context#restore 這里的好處是上下文可以保持一堆狀態,因此,如果您在函數內部調用一個函數,它也可以安全地使用保存/恢復對。

你應該.save上下文的狀態你翻譯它。 這也將具有簡化您的clearRect調用的優勢:

ctx.clearRect(0, 0, c.width, c.height);  // simplified
ctx.save();                              // save the current state
ctx.translate(c.width/2,c.height/2);
ctx.strokeStyle = "red";
ctx.moveTo(0-c.width/2,0);
ctx.beginPath();
for(i=0-c.width/2;i<=c.width;i++){
    ctx.lineTo(i,eval(equation.replace(/x/g,i.toString()))*-1);
};
ctx.stroke();
ctx.closePath();
ctx.restore();                           // to back to the original (untranslated) state

暫無
暫無

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

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