[英]Canvas and Javascript update rect and display custom text string
我希望用户点击一个调整大小按钮来改变一个矩形的大小,但也修改一个文本字符串来宣布新的大小和平方英寸......查看代码中的注释......
html 文档....
<input type="button" id="increaseBoxWidth" value="Make Box Wider">
<input type="button" id="decreaseBoxWidth" value="Make Box Narrower">
<input type="button" id="increaseBoxHeight" value="Make Box Taller">
<input type="button" id="decreaseBoxHeight" value="Make Box Shorter">
然后是javascript.....
window.addEventListener("load", eventWindowLoaded, false);
function eventWindowLoaded () {
initializeThings();
}
function initializeThings() {
... canvas, context and such.....
var boxWidth = 5;
var boxHeight = 3;
var boxSquareInches = 15;
var message = "box is 5 inches wide and 3 inches tall... and the total square inches is 15"
... is only one "var" declared for all these listeners?
var formElement = document.getElementById("increaseBoxWidth");
formElement.addEventListener('click', boxWider, false);
formElement = document.getElementById("decreaseBoxWidth");
formElement.addEventListener('click', boxNarrower, false);
formElement = document.getElementById("increaseBoxHeight");
formElement.addEventListener('click', boxTaller, false);
formElement = document.getElementById("decreaseBoxHeight");
formElement.addEventListener('click', boxShorter, false);
function boxWider(){
if (boxWidth < 10) {
boxWidth += 1;
boxSquareInches = boxWidth * boxHeight;
message = "Hey there... your new box size is + boxWidth + inches by + boxHeight+ inches... and the total square inches is + boxSquareInches +"
drawScreen()
}
}
/// THREE MORE FUNCTIONS???? FOR NARROWER, TALLER AND SHORTER????
function drawScreen(){
...
context.fillRect(0,0,boxWidth,boxHeight);
context.fillText (message, 10, 100);
}
}
... 是不是为所有这些听众声明了一个“var”?
不,每个元素都需要用唯一的名称声明,否则,当用户单击一个按钮或另一个按钮时,您的程序无法区分。 像这样的东西:
var iw = document.getElementById("increaseBoxWidth");
iw.addEventListener('click', boxWider, false);
var dw = document.getElementById("decreaseBoxWidth");
dw.addEventListener('click', boxNarrower, false);
var ih = document.getElementById("increaseBoxHeight");
ih.addEventListener('click', boxTaller, false);
var dh = document.getElementById("decreaseBoxHeight");
dh.addEventListener('click', boxShorter, false);
/// 三个更多的功能???? 对于更窄、更高和更矮的人????
是的,这将是接下来要做的事情。 就像你对boxWider()
所做的boxWider()
请注意您的字符串:您需要拆分字符串以便将变量与您的文本连接起来。 换句话说, +
号和变量名不在引号内。 像这样:
message = "Hey there... your new box size is" + boxWidth + "inches by" + boxHeight + "inches... and the total square inches is" + boxSquareInches;
附加说明:在 JavaScript 中,注释以两个//
开始,而不是...
希望有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.