Reputation: 139
I'm developing a web app that lets the user click a button (with a number or mathematical symbol value) and then click in a workspace and have the corresponding character appear. So far, this is what I have for the Javascript:
<script type="text/javascript">
var mathCanvas = document.getElementById("matharea");
var ctx = mathCanvas.getContext("2d");
ctx.font="18px Arial";
var boolOne = 0;
var boolTwo = 0;
function insertOne(){
boolOne = 1;
};
function insertTwo(){
boolTwo = 1;
};
mathCanvas.onclick = function(event){
var x = event.offsetX;
var y = event.offsetY;
if(boolOne == 1){
ctx.fillText("1",x-5,y-5);
boolOne = 0;
};
if(boolTwo == 1){
ctx.fillText("2",x-5,y-5);
boolTwo = 0;
};
};
</script>
Right now I'm only testing using the 1 and 2 buttons. In the two 'if' statements I set the boolean value back to 0 after the number is placed, but obviously it would be better to allow the user to keep placing the corresponding number until another number button is pressed, instead of the one-shot functionality I have here. I can imagine resetting the boolean when another specific button is pressed, but how would I change it back to 0 when ANY other button is pressed?
Upvotes: 0
Views: 507
Reputation: 4868
You could change around your logic a little bit to make it a lot more flexible. Something like:
var placementCallback = function() {}
function onButton1Click() {
placementCallback = function(x, y) {
ctx.fillText('1', x-5,y-5);
}
}
function onButton2Click() {
placementCallback = function(x, y) {
ctx.fillText('2', x-5,y-5);
}
}
mathCanvas.onclick = function(event){
placementCallback(event.offsetX, event.offsetY);
}
This way, you don't have a massive if condition and you can build out as many buttons as you'd like (and it meets your "as many times as the user wants" requirement as well, provided you give their implementation for the placement callback that is.
Hope that helps.
Upvotes: 1