Thomas Moulton
Thomas Moulton

Reputation: 55

Why can I not get more than 2 variables to work on HTML5 Canvas and JavaScript?

I'm using this code:

<!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");
    var $text3=document.getElementById("sourceText3");

    $text1.onkeyup=function(e){ redrawTexts(); }
    $text2.onkeyup=function(e){ redrawTexts(); }
    $text3.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");
        wrapText(ctx,$text3.value,200,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>
    <input id=sourceText3 type=text><br>
    <canvas id="canvas" width="900" height="600" style="border:1px solid #000000;"></canvas>
</body>
</html>

And I can't seem to get "sourceText3" variable to work?

Basically the code allows real time editing of an html5 canvas, and I cant get more than 2 text inputs to work?

I ideally would like many more input boxes, for a different project I am working on.

Thanks so much.

Tom

Upvotes: 3

Views: 49

Answers (1)

savvamadar
savvamadar

Reputation: 294

Try putting the ids in quotes so

id=sourceText1 -> id="sourceText1"

That could do the trick.

Upvotes: 2

Related Questions