Html5-canvas Bug

时间:2015-12-27 21:14:51

标签: javascript html5 html5-canvas

所以我用<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)的位置,除非我完全重置页面,否则我无法将其更改回来。所以我的问题是我的功能正在发生什么问题,我该如何解决? 提前谢谢。

2 个答案:

答案 0 :(得分:1)

getContext不创建新的上下文,每次都返回相同的上下文。在获得上下文后,您将其翻译,并且只是保持翻译。

要修复,请在功能结束时将上下文翻译一次或在使用后将其翻译回来。

顺便说一句,一种不改变上下文几何(翻译,旋转,缩放)的简单方法是在函数开头使用context#save,在结尾使用context#restore。这里的好处是上下文保持一堆状态,所以如果你在函数中调用一个函数,它也可以安全地使用保存/恢复对。

答案 1 :(得分:0)

在翻译之前,您应该.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