开发者

Why are bar graphs acting so strangely? html5 canvas, and javascript

开发者 https://www.devze.com 2023-02-08 04:36 出处:网络
For my first foray into html5, I\'m trying to make a scoreboard for the 开发者_StackOverflowgame Farkle.

For my first foray into html5, I'm trying to make a scoreboard for the 开发者_StackOverflowgame Farkle.

I have figured out how to make a lame looking but functional graph system for up to five players, but I cannot figure out how to have it update more than once.

I realize that my code could be much better, but I didn't want to write helper functions until I was sure how it would work.

As it is now, I'm getting weird behavior from the boxes. Rather than adding the "tally" to the total score, and drawing a box to reflect the new score, it does something that I don't understand. Try typing 10, and then 90 for the same player to see what I mean.

Here is a "working" version, so that you can see my problem. http://jsfiddle.net/kBJB4/

edit: It seems like it rather than adding the numbers normally, eg. 1+1=2, it is doing some kind of append thing, eg. 1+1=11. I have no idea why.


The prompt() function call returns a string. So the variable tally in the following statement

var tally = prompt("score?");

is actually a string. So applying + operator to a string operand and an integer operand results in treating both the operands as string and performing string concatenation instead of integer addition. A simple fix is to convert the return value of prompt() to integer like:

var tally = parseInt(prompt ("Score?"));


Update: @Suresh Kumar's answer is a bit cleaner. Leaving mine up though.

Your code: player1 += tally; is treating both variables as strings.

Use parseInt to force it to use numbers:

player1 = parseInt(player1) + parseInt(tally);

Note: Trying to shortcut this with player1 += parseInt(tally); doesn't work, because it's still treating player1 as a string

0

精彩评论

暂无评论...
验证码 换一张
取 消