2010-12-30 11 views
0

キャンバスタグを使用して図形を描画できるようにしようとしましたが、新しい線を描画すると他の線はすべて消えます。 Try It (copy+paste to the textarea and click the "Edit and Click Me >>" button)。私は、この問題が5つの最も一般的なブラウザ(IE7,8とIE9betaを含む)に存在することを言及する必要があります。<canvas>修復の問題

コード:

<!DOCTYPE html> 
<html> 
<head> 
<!-- ... --> 
<!-- (a script used to support canvas in IE7,8) --><!--[if lte IE 8]> 
<script type="text/javascript" src="http://explorercanvas.googlecode.com/svn/trunk/excanvas.js"></script> 
<![endif]--> 
<script type="text/javascript">//<![CDATA[ 
    var cnvs, cntxt; 
    window.onload = function() { 
     cnvs = document.getElementById("cnvs"); 
     cntxt = cnvs.getContext("2d"); 
     //... 
    }; 

    var lastX, lastY; 
    function beginLine(x, y) { 
     cntxt.moveTo(x, y); 
     cntxt.save(); 
     lastX = x; 
     lastY = y; 
     cnvs.setAttribute("onmousemove", "preview(event.clientX, event.clientY);"); 
     cnvs.setAttribute("onmouseup", "closeLine(event.clientX, event.clientY);"); 
    } 

    function closeLine(x, y) { 
     cntxt.lineTo(x, y); 
     cntxt.stroke(); 
     cntxt.save(); 
     cnvs.removeAttribute("onmousemove"); 
     cnvs.removeAttribute("onmouseup"); 
    } 

    function preview(x, y) { 
     cntxt.beginPath(); 
     cntxt.clearRect(0, 0, cnvs.width, cnvs.height); 
     cntxt.restore(); 
     cntxt.moveTo(lastX, lastY); 
     cntxt.lineTo(x, y); 
     cntxt.stroke(); 
    } 
//]]></script> 
</head> 
<body> 
    <!-- ... --> 
    <canvas id="cnvs" style="position:absolute;top:0;left:0;border:1px black solid;" onmousedown="beginLine(event.clientX, event.clientY);"></canvas> 
    <p style="margin-top:200px;">(click and drag the mouse to draw a line)</p> 
</body> 
</html> 

それはおそらく保存/復元間違いだが、私はそれを見つけることができません。


私は2つの異なるフォーラム試してみました:

を誰もが問題が何であるかを伝えることができませんでした。

答えて

2

あなたはの意味を誤解して、を復元しました。の方法を誤解しました。彼らはカンバス状態を保存しません。 意味、あなたはcanvas.save()を発行したとき、あなたがのfillStylestrokeStyle線幅たlineJoinを保存しています。あなたの問題へ

最も簡単な解決策は、メモリ内の同じサイズの別のキャンバスを維持し、その後、マウスボタンが離されると、clearRectのdrawImage方法を使用することです。または、線を配列にプッシュして毎回描画することもできます(既存のキャンバスに描画するよりも速いかもしれません)。

さらに、もう1つのヒントはです。clearRectです。それは、この方法は信じられないほど遅いことが判明しました。あなたのケースでは、パフォーマンスに多少の重大な影響を与えるために頻繁にそれを使用していませんが、同じの幅の高さはをキャンバスオブジェクトに割り当てる方がはるかに高速です。

+0

特に、変換の保存(回転、平行移動、縮尺)を「保存」することがあります。 – Phrogz