我正在使用此代码:
<!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,canvas.width,canvas.height);
wrapText(ctx,$text1.value,20,60,100,24,"verdana");
wrapText(ctx,$text2.value,150,$text3.value,200,"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,y);
line = words[n] + ' ';
y += lineHeight;
}
else {
line = testLine;
}
}
context.fillText(line,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>
而且我似乎无法使“ sourceText3”变量正常工作?
基本上,代码允许实时编辑html5画布,而我不能获得2个以上的文本输入来工作?
理想情况下,我想要更多的输入框,用于我正在从事的另一个项目.
非常感谢.
汤姆
最佳答案
尝试将ID放在引号中,这样
id=sourceText1 -> id="sourceText1"
那可以解决问题.