【发布时间】:2019-08-06 22:35:29
【问题描述】:
我正在使用此代码:
<!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 画布,但我不能让超过 2 个文本输入工作?
理想情况下,我想要更多的输入框,用于我正在从事的不同项目。
非常感谢。
汤姆
【问题讨论】:
-
我刚刚将您的 HTML 粘贴到 codepen.io 的新页面中,所有三个输入都有效。
-
你能描述一下你在这里看到了什么吗?任何控制台错误或任何东西?
-
@borrascador,你没看错!你有什么想法为什么不能在使用 Firefox 加载的 Sublime 文本中工作?
-
大家好,控制台没有显示任何错误。所以最后我删除了整个文件,重新启动了我的系统,创建了一个新文件并从上面的代码中复制粘贴。出于某种原因,这已经奏效了。非常感谢您的帮助。
-
@ThomasMoulton 抱歉,我没有任何使用 Sublime 文本的经验,但我很高兴你能帮上忙。至少您知道如果再次发生这种情况,您应该在线进行健全性检查。
标签: javascript jquery html html5-canvas