为什么在HTML5 Canvas和JavaScript上不能使用两个以上的变量?

前端之家收集整理的这篇文章主要介绍了为什么在HTML5 Canvas和JavaScript上不能使用两个以上的变量? 前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我正在使用此代码

  1. <!doctype html>
  2. <html>
  3. <head>
  4. <link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
  5. <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
  6. <style>
  7. body{ background-color: ivory; }
  8. canvas{border:1px solid red;}
  9. </style>
  10. <script>
  11. $(function(){
  12. var canvas=document.getElementById("canvas");
  13. var ctx=canvas.getContext("2d");
  14. var $text1=document.getElementById("sourceText1");
  15. var $text2=document.getElementById("sourceText2");
  16. var $text3=document.getElementById("sourceText3");
  17. $text1.onkeyup=function(e){ redrawTexts(); }
  18. $text2.onkeyup=function(e){ redrawTexts(); }
  19. $text3.onkeyup=function(e){ redrawTexts(); }
  20. function redrawTexts(){
  21. ctx.clearRect(0,canvas.width,canvas.height);
  22. wrapText(ctx,$text1.value,20,60,100,24,"verdana");
  23. wrapText(ctx,$text2.value,150,$text3.value,200,"verdana");
  24. }
  25. function wrapText(context,text,x,y,maxWidth,fontSize,fontFace){
  26. var words = text.split(' ');
  27. var line = '';
  28. var lineHeight=fontSize;
  29. context.font=fontSize+" "+fontFace;
  30. for(var n = 0; n < words.length; n++) {
  31. var testLine = line + words[n] + ' ';
  32. var metrics = context.measureText(testLine);
  33. var testWidth = metrics.width;
  34. if(testWidth > maxWidth) {
  35. context.fillText(line,y);
  36. line = words[n] + ' ';
  37. y += lineHeight;
  38. }
  39. else {
  40. line = testLine;
  41. }
  42. }
  43. context.fillText(line,y);
  44. return(y);
  45. }
  46. }); // end $(function(){});
  47. </script>
  48. </head>
  49. <body>
  50. <h4>Type text to wrap into canvas.</h4>
  51. <input id=sourceText1 type=text>
  52. <input id=sourceText2 type=text>
  53. <input id=sourceText3 type=text><br>
  54. <canvas id="canvas" width="900" height="600" style="border:1px solid #000000;"></canvas>
  55. </body>
  56. </html>

而且我似乎无法使“ sourceText3”变量正常工作?

基本上,代码允许实时编辑html5画布,而我不能获得2个以上的文本输入来工作?

理想情况下,我想要更多的输入框,用于我正在从事的另一个项目.

非常感谢.

汤姆

最佳答案
尝试将ID放在引号中,这样

  1. id=sourceText1 -> id="sourceText1"

那可以解决问题.

猜你在找的HTML相关文章