我自己在javascript方面并不差,但我现在想知道几天是否有可能。如果是,谁能帮助我?
我需要构建一个单页应用程序,而我正处于早期阶段。现在我目前陷入困境的一部分是。
我希望将不同类型的问题加载到画布中。
=> 画布的爪哇
var Question = 'questions'; //<= **this is the part that needs to be corrected**
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
ctx.font = 'italic 18px Arial';
ctx.textAlign = 'center';
ctx. textBaseline = 'middle';
ctx.fillStyle = 'red'; // a color name or by using rgb/rgba/hex values
ctx.fillText(Question,100,50)// text and position
更清楚一点。我有10个问题。我想通过单击按钮将它们一一加载到画布中。但是我不知道如何将.txt文件加载到画布中,任何人都可以帮助我吗?
提前感谢,任何帮助都会得到很多
您需要发出 AJAX GET 请求、加载文本文件数据并使用响应文本作为问题。像这样:
var request = new XMLHttpRequest();
request.open('GET', 'question.txt', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400){
var Question = request.responseText;
ctx.fillText(Question, 100, 50)
}
};
request.send();
这是一个基本的想法。我想,根据文件内容,您可能希望在画布上呈现之前以某种方式处理响应文本。
演示:http://plnkr.co/edit/3OX8xI7h43CSlcuWowQ5?p=preview
您只需要 1) 问题列表和 2) 在设置新问题时重置画布:
var questionIndex = 0;
var questions = [
"question 1",
"question 2",
"question 3"
];
function nextQuestion() {
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.font = 'italic 18px Arial';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillStyle = 'red'; // a color name or by using rgb/rgba/hex values
ctx.fillText(questions[questionIndex++], 100, 50)// text and position
if (questionIndex > questions.length - 1) {
questionIndex = 0;
}
}
..
<canvas id="myCanvas"></canvas>
<input type="button" id="btnNext" onclick="nextQuestion()" value="Next Question" />
http://jsfiddle.net/oehq2c0p/