ここに、あなたの現在の例で動作するコードがあります。しかし、ひどく欠陥があります - 私はそれを非常に明確にしたいと思います。
0)テキストを適切に覆うために消去矩形を得るには、4ピクセルを追加する必要がありました。なぜこれが必要なのかわからない、またはこれをクエリ/計算する方法 - イメージエディタを使用しました。あなたのテキストのサイズが違っていたら、私は4よりも異なる「マジックナンバー」を使う必要があると思います。
1)バックグラウンドが白でない場合、あなたは単色ではなく模様を持っています。
2)キーストロークごとにテキスト全体が消去され、再描画されます。理想的に言えば、必要な場合にのみクリアしてください。つまり、テキストが長くなり、新しい文字が新しい文字まで同じであれば、消去するものは何もありません。
3)コードの脆弱性をさらに調べるには、あまりにも疲れました。
4)実際に私は約99.9999999%の確かにこの種のタスクを実行するコードを見つけることができます。これははるかに堅牢で、プロダクション対応のコードです。
このコードは、「動作するハック」にすぎません。私がそれを単にコメントとして投稿できるのであれば、私はそうするでしょう。
おそらく、より良い選択肢は、白を色として使用して再度テキストを描画することです。ただし、アンチエイリアシングのためにこれがうまくいかないと感じていますが、これは微妙なアウトラインを残します。既存のテキストを適切にカバーする。
コードが適切でない場合は、領収書とともに返却していただき、全額返金してください。 :笑:言っ
は
、ここに行く:
<!DOCTYPE html>
<html>
<head>
<script>
function byId(id){return document.getElementById(id);}
window.addEventListener('load', onDocLoaded, false);
var textPosX = 10, textPosY = 50;
var defaultText = "This is a apple";
var curText = defaultText;
var defaultFont = "20px Georgia";
function onDocLoaded(evt)
{
// add event listener to the input element, this will fire any time (text) input is received
byId('sourceText1').addEventListener('input', onSourceTextInput, false);
var c = byId("myCanvas");
var ctx = c.getContext("2d");
ctx.font = defaultFont;
ctx.fillText(defaultText, textPosX, textPosY);
ctx.font = "30px Verdana";
// Create gradient
var gradient = ctx.createLinearGradient(0, 0, c.width, 0);
gradient.addColorStop("0", "magenta");
gradient.addColorStop("0.5", "blue");
gradient.addColorStop("1.0", "red");
// Fill with gradient
ctx.fillStyle = gradient;
ctx.fillText("Big smile!", 10, 90);
}
function onSourceTextInput(evt)
{
var can = byId('myCanvas');
var ctx = can.getContext('2d');
var curTextWidth, curTextHeight;
curTextWidth = ctx.measureText(curText).width;
curTextHeight = 20;
var curStyle = ctx.fillStyle;
ctx.fillStyle = "white";
ctx.fillRect(textPosX, (textPosY-curTextHeight)+4, curTextWidth, curTextHeight);
ctx.fillStyle = 'BLACK';
ctx.font = defaultFont;
ctx.fillText(this.value, textPosX, textPosY);
ctx.fillStyle = curStyle;
curText = this.value;
}
</script>
</head>
<body>
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">Your browser does not support the HTML5 canvas tag.</canvas>
<input id="sourceText1" type='text'/>
</body>
</html>
は、いくつかのコードを教えてください。 – hindmost
私はロードしています。 –
あなたは** minimal **と** verifiable **の例で質問を更新します。 – evolutionxbox