无法在HTML 5中清除画布工作区

时间:2014-03-28 05:21:25

标签: javascript html5 canvas

不知怎的,我无法在画布标签中清楚地看到画布,它只清除了一些部分,我将canvas.witdh和height作为参数。最初它应该在单击一个按钮并且触发clearGraph()函数并重绘时清除所有内容。请帮帮我。 你可以从这里查看。 http://jsfiddle.net/qH2Lr/1/     

    function init() {

    // data sets -- set literally or obtain from an ajax call
    var dataName = [ "You", "Competitors" ];
    var dataValue = [ 2600, 4000];
        // set these values for your data
        numSamples = 2;
        maxVal = 5000;
        var stepSize = 1000;
        var colHead = 50;
        var rowHead = 60;
        var margin = 10;
        var header = "Millions"
       var can = document.getElementById("can");
        ctx = can.getContext("2d");
        ctx.fillStyle = "black"
        yScalar = (can.height - colHead - margin) / (maxVal);
        xScalar = (can.width - rowHead) / (numSamples + 1);
        ctx.strokeStyle = "rgba(128,128,255, 0.5)"; // light blue line
        ctx.beginPath();
        // print  column header
        ctx.font = "14pt Helvetica"
        ctx.fillText(header, 0, colHead - margin);
        // print row header and draw horizontal grid lines
        ctx.font = "12pt Helvetica"
        var count =  0;
        for (scale = maxVal; scale >= 0; scale -= stepSize) {
            y = colHead + (yScalar * count * stepSize);
            ctx.fillText(scale, margin,y + margin);
            ctx.moveTo(rowHead, y)
            ctx.lineTo(can.width, y)
            count++;
        }
        ctx.stroke();
        // label samples  ctx.shadowColor = 'rgba(128,128,128, 0.5)';
        ctx.shadowOffsetX = 20;
        ctx.shadowOffsetY = 1;
        // translate to bottom of graph and scale x,y to match data
        ctx.translate(0, can.height - margin);
        ctx.font = "14pt Helvetica";
        ctx.textBaseline = "bottom";
        for (i = 0; i < 4; i++) {
            calcY(dataValue[i]);
            ctx.fillText(dataName[i], xScalar * (i + 1), y - margin);
        }
        // set a color and a shadow
        ctx.fillStyle = "green";

        ctx.scale(xScalar, -1 * yScalar);
        // draw bars
        for (i = 0; i < 4; i++) {
            ctx.fillRect(i + 1, 0, 0.5, dataValue[i]);
        }

    }

    function calcY(value) {
        y = can.height - value * yScalar;
    }

    function clearGraph() {

        var canvas = document.getElementById("can");
        var ctx = canvas.getContext("2d");

        // Will always clear the right space
        ctx.clearRect(0, 0, canvas.width, canvas.height);


    }
</script>

1 个答案:

答案 0 :(得分:1)

您正在对上下文进行许多更改,例如缩放和翻译。

这些也会影响clearRect()。在这种情况下,我建议使用save()restore()方法。 save()存储上下文的当前。转换:

ctx = can.getContext("2d");

ctx.save();    // after obtaining the context

... rest of code ...

ctx.restore(); // before clearing
ctx.clearRect(0, 0, can.width, can.height);

现在你可以看到它按预期工作:

<强> Modified fiddle

当然,在绘制完所有内容后立即清除可能不是真正的意图,而是表明它确实有用(当你最终需要它时 - 如果你打算重新绘制图形,就把它放在代码中)。