我正在使用这段代码:
<!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>
而且我似乎无法让“sourceText3”变量工作?
基本上代码允许实时编辑 html5 Canvas ,但我不能让超过 2 个文本输入工作?
理想情况下,我想要更多的输入框,用于我正在进行的不同项目。
非常感谢。
汤姆
最佳答案
尝试将 ID 放在引号中
id=sourceText1 -> id="sourceText1"
这可以解决问题。
关于javascript - 为什么我不能获得超过 2 个变量来处理 HTML5 Canvas 和 JavaScript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55189514/