Reputation: 103
i'm not to bad at javascript myself but i am wondering for a few days at this moment wheter it's possible or not. And if it is, who can help me ?
i need to build a single page application , and i am at the early phase. now one part where i am stuck at the moment is.
i wish to load different kind of questions into a canvas.
=> java of the canvas
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
to be more clear. i have let's say 10 questions. i want to load them one by one into the canvas by clicking a button. but i can't figure out how to load .txt files into the canvas can anyone PLEASE help me ?
thanx in advance , any help would be much appriciated
Upvotes: 2
Views: 908
Reputation: 3110
You just need 1) a list of questions and 2) to reset the canvas when setting a new question:
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" />
Upvotes: 0
Reputation: 193311
You need to issue AJAX GET request, load text file data, and use response text as a question. Something like this:
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();
This is a basic idea. I guess, depending on file contents you might want to process response text somehow before rendering on the canvas.
Upvotes: 2