1

I'm creating a simple game using the HTML5 canvas and the jCanvaScript library.

//JavaScript
function start() {
    jc.start("drawingCanvas", 380);
    text = jc.text('score: ' + score, 10, 10);
    clock = jc.text(round / 2, 285, 145);
    var millisecondsToWait = 500;
    inter = setInterval(nextRound, millisecondsToWait);
}

function nextRound() {
    round--;
    if(round % 2 == 0){
        clock.string(round / 2);
    }
    if (round == 0) {
        endGame();
    } else {
        draw();
    }
}

function draw() {
    var shape = jc.circle(random() * 300, random() * 100, random() * 10, randomRgba(), 1);
    shape.click(destroy);
    shape.animate({
        x : random() * 300,
        y : random() * 100,
        radius : random() * 100
    }, random() * 2000);
}
function destroy() {
    score += Math.round(100 - this._radius);
    text.string('score: ' + score);
    this.color('#ff0000');
    this.animate({
        radius : 0
    }, 1000);
}

the html is too easy:

<!DOCTYPE HTML>
<html>
    <head>
        <script src="http://jcscript.com/data/js/jCanvaScript.1.5.18.min.js"></script>
        <script src="js/canvasWithLibraries.js"></script>
        <link rel="stylesheet" href="css/canvaslib.css" />
        <title>Canvas with libraries demo</title>
    </head>
    <body>
        <canvas id="drawingCanvas">your browser does not support the canvas element</canvas>
    </body>
</html>

QUESTION:

As you can see from the code, everytime I click on a shape, the shape should turn red and grow smaller until it vanishes. This seems to be working, sometimes. When you test this code, you'll notice that the click seems to respond on different shapes or not at all or just random. Does anyone have an idea what the problem is?

I'm guessing this is all on a single thread and the loop doens't get interrupted properly.

Loktar
  • 34,764
  • 7
  • 90
  • 104
Yoeri
  • 2,249
  • 18
  • 33
  • After messing with a local copy I don't think its your code, I think its the library and how it handles the click events per object. Objects are assigned to layers, and it seems like it can be picky when clicking through layers, if theres a lot of them. – Loktar Nov 20 '12 at 16:05
  • hey thanks for taking the time. I'll have to try a different library then. Pitty, this one is quite straightforward. – Yoeri Nov 20 '12 at 20:12
  • 1
    I found the problem, see my answer – Yoeri Feb 26 '13 at 21:43

2 Answers2

1

Okay I found out what was wrong. I set the size of my canvas via CSS, which you may never do, because CSS resizes and stretches the canvas, without javascript knowing.

So I was clicking on shapes, transformed by CSS... not the actual shape in javascript/canvas.

I put height and width inline in the canvas and now it works like a charm.

You can see it working here: live example

Yoeri
  • 2,249
  • 18
  • 33
0

You need to return false from event function if you want to have event working only on first shape.

Alex Savin
  • 286
  • 2
  • 6