HTML canvas在keypress上动态地将文本框值输入到画布中

时间:2014-08-03 07:41:38

标签: javascript jquery html5 html5-canvas

分别有三个文本框textbox1,textbox2和textbox3

我想在用户进入文本框时将这些文本框的值放入画布(cnv)

并删除该值,因为用户将其从文本框中删除。

问题是,当我尝试删除一个文本框的值时,画布中的所有值都被清除。但我想阻止旧的价值观。

2 个答案:

答案 0 :(得分:1)

试试这个:

http://jsfiddle.net/9Dhu6/

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.font = "30px Arial";
var y=10
function canvasFillTxt(txt){
    ctx.fillText(txt,10,y);
    y=y+20
}
$('input').on('change',function(){
    canvasFillTxt($(this).val())
})

我希望你正在寻找...

答案 1 :(得分:0)

当焦点离开文本框时,change事件才会被触发。

对于按键式响应,请在文本框中监听keyup事件,而不是change事件。

示例代码:

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
    body{ background-color: ivory; }
    canvas{border:1px solid red;}
</style>
<script>
$(function(){

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

    var $text1=document.getElementById("sourceText1");
    var $text2=document.getElementById("sourceText2");

    $text1.onkeyup=function(e){ redrawTexts(); }
    $text2.onkeyup=function(e){ redrawTexts(); }

    function redrawTexts(){
        ctx.clearRect(0,0,canvas.width,canvas.height);   
        wrapText(ctx,$text1.value,20,60,100,24,"verdana");
        wrapText(ctx,$text2.value,150,60,100,24,"verdana");
    }

    function wrapText(context, text, x, y, maxWidth, fontSize, fontFace){
      var words = text.split(' ');
      var line = '';
      var lineHeight=fontSize;

      context.font=fontSize+" "+fontFace;

      for(var n = 0; n < words.length; n++) {
        var testLine = line + words[n] + ' ';
        var metrics = context.measureText(testLine);
        var testWidth = metrics.width;
        if(testWidth > maxWidth) {
          context.fillText(line, x, y);
          line = words[n] + ' ';
          y += lineHeight;
        }
        else {
          line = testLine;
        }
      }
      context.fillText(line, x, y);
      return(y);
    }

}); // end $(function(){});
</script>
</head>
<body>
    <h4>Type text to wrap into canvas.</h4>
    <input id=sourceText1 type=text>
    <input id=sourceText2 type=text><br>
    <canvas id="canvas" width=300 height=300></canvas>
</body>
</html>