Solved

HTML5 - canvas, path, events - events for two different paths / objects?

Posted on 2015-02-09
5
140 Views
Last Modified: 2015-02-10
Learning HTML5 and "canvas"

http://jsfiddle.net/tomjsfiddle/n4ay029b/

( you may need to pick jQuery to see some aspects of this work correctly, I am not sure pure JS does it)

You can click inside the circle and it will change color, click outside the circle and it will change color.  But BOTH circles are responding to the event.  I want the circles to operate independently; have different colors and different responses to button clicks.

Part of my problem is I do not understand the canvas, context, path, or events as well as I need to.  This will come with more study and more time I am sure.

But a little help now would be much appreciated!!

Thank you,

Tom
0
Comment
Question by:knowlton
  • 3
  • 2
5 Comments
 
LVL 35

Expert Comment

by:Robert Schutt
Comment Utility
You can do this with more than 1 canvas but not, as your current code was trying to do, with more than 1 context pointing at the same canvas. This is simply due to the context implementation. More info here. Specifically it states, after the first getContext("2d") is done, the second call will:
Return the same object as was return the last time the method was invoked with this same argument.
I saved a new version of your fiddle using 2 canvas elements. I changed some more things:
- use css more, position the 2 canvas elements at the same position using a container;
- moved gameboard1 after gameboard2 in the html so it can receive the mouse click now that the 2 canvas elements are overlapping;
- removed the need for jQuery as you were only using that for the css and domready event.

HTML:
<!DOCTYPE HTML>
<body>
word game
<div id="a"></div>
<div id="container">
<div id="Div1"><canvas id="gameboard2" width="800" height="600"></canvas></div>
<div id="canvasdiv"><canvas id="gameboard1" width="800" height="600"></canvas></div>
</div>
</body>

Open in new window


CSS:
#container {
    position: relative;
}
#gameboard1, #gameboard2 {
    border: 2px solid green;
    position: absolute; /* inside container */
}

Open in new window


JS:
var c_canvas1 = document.getElementById("gameboard1");
var c_canvas2 = document.getElementById("gameboard2");

c_canvas1.addEventListener("click", mousewasclickedone, false);

//Can I create mulitple objects on a canvas and keep them independent?
//Multiple canvases?

var context1 = c_canvas1.getContext("2d");
var context2 = c_canvas2.getContext("2d");

drawCircle(300, 300, false, context1);
drawCircle(150, 80, false, context2);


function drawCircle(x, y, selected, whichContext) {
    
    whichContext.beginPath();
    whichContext.strokeStyle = "#000";
    whichContext.arc(x, y, 50, 0, Math.PI * 2, false);
    whichContext.stroke();
}



function mousewasclickedone(e) {
    var rect1 = c_canvas1.getBoundingClientRect(),
        x1 = e.clientX - rect1.left,
        y1 = e.clientY - rect1.top,
        inPath1 = context1.isPointInPath(x1, y1),
        inPath2 = context2.isPointInPath(x1, y1);
    
    context1.fillStyle = inPath1 ? "#faa" : "#bbb";
    context1.fill();
    context2.fillStyle = inPath2 ? "#faa" : "#bbb";
    context2.fill();
}

Open in new window

0
 
LVL 35

Accepted Solution

by:
Robert Schutt earned 500 total points
Comment Utility
I also saved a different version of your fiddle using only 1 canvas and context: http://jsfiddle.net/n4ay029b/2/

Here I use an array to remember the different circles and test them in a loop. In this way it would be much easier to add more circles to the board.
var c_canvas1 = document.getElementById("gameboard1");
var allCircles = [];

c_canvas1.addEventListener("click", mousewasclickedone, false);

//Can I create mulitple objects on a canvas and keep them independent?
//Multiple canvases?

var context1 = c_canvas1.getContext("2d");

drawCircle(300, 300, false, context1);
drawCircle(150, 80, false, context1);


function drawCircle(x, y, selected, whichContext) {
    
    whichContext.beginPath();
    whichContext.strokeStyle = "#000";
    whichContext.arc(x, y, 50, 0, Math.PI * 2, false);
    whichContext.stroke();
    // add to global array for comparison later
    allCircles.push({x:x, y:y, r:50});
}



function mousewasclickedone(e) {
    var rect1 = c_canvas1.getBoundingClientRect(),
        x1 = e.clientX - rect1.left,
        y1 = e.clientY - rect1.top,
        inPath1;
    
    for (var c = 0; c < allCircles.length; c++) {
        context1.beginPath();
        context1.arc(allCircles[c].x, allCircles[c].y, allCircles[c].r, 0, Math.PI * 2, false);
        inPath1 = context1.isPointInPath(x1, y1);
        context1.fillStyle = inPath1 ? "#faa" : "#bbb";
        context1.fill();
    }
}

Open in new window

0
 
LVL 5

Author Closing Comment

by:knowlton
Comment Utility
Wow - well done.

Seems odd to beginPath( ) but not closePath( )?
0
 
LVL 35

Expert Comment

by:Robert Schutt
Comment Utility
cool right, I hope you have more questions so we can see you and your game evolve here.

closePath is not needed on a full circle, you could use it when drawing more than 1 circle to avoid the line between them but it's enough to use beginPath before drawing the next one.

closing is also handy when you draw a triangle for example, using closePath avoids having to moveTo the initial point again. Same goes for a closed partial circle etc.
0
 
LVL 5

Author Comment

by:knowlton
Comment Utility
Okay.  So it is kind of like "close the shape"
0

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Form submit issue 11 51
Cannot scroll down on html page 2 25
jqplot Pie Chart 2 11
Return data with AJAX, JQUERY and PHP 13 26
Use these top 10 tips to master the art of email signature design. Create an email signature design that will easily wow recipients, promote your brand and highlight your professionalism.
This article discusses how to create an extensible mechanism for linked drop downs.
In this tutorial viewers will learn how to code links for mobile sites that, once clicked, send a call or text to a specified number. For a telephone link (once clicked, calls a number), begin with a normal "<a href=" link tag. For the href, specify…
In this tutorial viewers will learn how to embed an audio file in a webpage using HTML5. Ensure your DOCTYPE declaration is set to HTML5: : The declaration should display (CODE) HTML5 is supported by the most recent versions of all major browsers…

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now