如何为每个正确的答案制作一个简单的图表

时间:2014-04-06 18:52:03

标签: javascript html canvas

我明天会有一个很大的测试,我不太确定每次得到正确答案时如何绘制图表,也无法找到/寻找一个好的解决方案。简单地说,我希望每次我在JAVASCRIPT中回答正确的时候,在柱子/柱子上添加x高度。

如果您可以告诉我如何操作,在使用此网站上的代码时:http://www.javascriptsource.com/miscellaneous/basic-javascript-quiz.html这太棒了!

编辑: 柱/柱塞可能是这样的:(不确定)。

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.fillStyle="#FF0000";
ctx.fillRect(0,0,150,100); 

编辑2:

<script>
var score = 0;
var questions = [
    ['How many moons does Earth have?', 1],
    ['How many moons does Saturn have?',31],
    ['How many moons does Venus have?', 0]
];

for (var i=0; i<questions.length; i++) {
 askQuestion(questions[i]);
}
function askQuestion(question) {
 var answer = prompt(question[0],'');
    if (answer == question[1]) {
        alert('Correct!');
        score++;
    } else {
        alert('Sorry. The correct answer is ' + question[1]);
    }
}


</script>
</head>

<body>
<script>
    var message = 'You got ' + score;
    message += ' out of ' + questions.length;
    message += ' questions correct.';
    document.write('<p>' + message + '</p>');
</script>

<canvas id="mycanvas"> </canvas>

</body>
</html>

1 个答案:

答案 0 :(得分:0)

这里有一些代码可以帮助您入门。

查看此代码并将其应用于您问题中的链接。

然后开始学习测试!!

给定一个数组,为每个问题保留正确答案的数量......

// an array that holds the count of correct responses for each answer

var answers=[];

for(var i=0;i<answers.length;i++){

    // how many correct answers for this question

    correctCount=answers[i];

    // make each bar 20 pixels apart on the x-axis

    answerX=i*20;

    // all bars grow from the same bottom line on the y-axis

    answerY=150;

    // all bars are the same width

    answerWidth=10;

    // each bar is 10 pixels taller for each correct answer

    answerHeight=correctCount*10;

    // draw this bar
    // a negative answerHeight will cause the bar to draw
    // upward instead of the usual downward

    ctx.fillRect(answerX,answerY,answerWidth,-answerHeight);

}