這裏有一些代碼可以用你當前的例子。然而,這是非常有缺陷的 - 我想說得很清楚。
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
好的我正在加載。 –
Pease使用**最小**和**可驗證**示例更新您的問題。 – evolutionxbox