2

現在、テキストを入力できるフォームがあり、キャンバス要素に表示されますが、バックスペースを押すとテキストが消えなくなり、テキストを再入力すると古いテキストの上に表示されます。

テキストの削除にも対応するキャンバス要素を取得する方法はありますか?

<!DOCTYPE html>
<html>


 <title>dropIn Print Generator</title>




<body>
<h1>dropIn Print Generator</h1>

<form method="post" action="run.php">
<p>brand name
<input type="text" id="brand" onkeyup="showBrand(this.value)" /></p>
<p>product name
<input type="text" id="product" onkeyup="showProductName(this.value)" /></p>
<p>product details
<input type="text" id="details" onkeyup="showProductDetail(this.value)" /></p>
<p>product sku
<input type="text" id="sku" /></p>
<p>product image
<input type="file" id="image" /></p>

</form>

<canvas id="mainCanvas" width="400" height="600" style="border:1px solid #000000;"></canvas>

<script>
    var canvas = document.getElementById('mainCanvas');
    var context = canvas.getContext('2d');

    // begin upper shape
    context.beginPath();
    context.moveTo(0, 0);
    context.lineTo(400, 0);
    context.lineTo(400, 300);
    context.lineTo(380, 30);
    context.lineTo(0, 50);
    context.lineTo(0, 0);

    // complete upper shape
    context.closePath();
    context.lineWidth = 1;
    context.strokeStyle = 'black';
    context.fillStyle = 'black';
    context.fill();
    context.stroke();

    // begin bottom shape
    context.beginPath();
    context.moveTo(400, 600);
    context.lineTo(200, 600);
    context.lineTo(400, 585);
    context.lineTo(400, 600);

    // complete bottom shape
    context.closePath();
    context.lineWidth = 1;
    context.strokeStyle = 'black';
    context.fillStyle = 'black';
    context.fill();
    context.stroke();




    function showBrand(str){  
        context.fillStyle = 'black';
        context.font = '20px sans-serif';
        context.textBaseline = 'bottom';
        context.fillText(str, 30, 100);          
        }

    function showProductName(str){   
        context.fillStyle = 'black';
        context.font = '30px sans-serif';
        context.textBaseline = 'bottom';
        context.fillText(str, 30, 135);
        }

    function showProductDetail(str){   
        context.fillStyle = 'black';
        context.font = '20px sans-serif';
        context.textBaseline = 'bottom';
        context.fillText(str, 30, 160);
      }

  </script>
</body>
</html>
4

1 に答える 1

0

キャンバスに新しいテキストをペイントするたびに、その前にキャンバスをクリアする必要があります。そうしないと、キャンバスに既に描画したものが残り、その上に描画することになります。

function clearCanvas() {
    // Redraw the background color over the top of the old text to 'clear' it.
    context.fillStyle = '#fff';
    context.fillRect(0, 0, canvas.width, canvas.height);
}

この関数の呼び出しを他の 3 つの描画関数の先頭に追加します。

于 2013-05-09T10:16:30.730 に答える