Html5-canvas Bug

Html5-canvas Bug

本文关键字:Bug Html5-canvas      更新时间:2023-09-26

所以我正在用<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