Solved

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

Posted on 2015-02-09
5
150 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
ID: 40599863
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
ID: 40599868
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
ID: 40600845
Wow - well done.

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

Expert Comment

by:Robert Schutt
ID: 40600933
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
ID: 40600945
Okay.  So it is kind of like "close the shape"
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article explains how to prepare an HTML email signature template file containing dynamic placeholders for users' Azure AD data. Furthermore, it explains how to use this file to remotely set up a department-wide email signature policy in Office …
Is your Office 365 signature not working the way you want it to? Are signature updates taking up too much of your time? Let's run through the most common problems that an IT administrator can encounter when dealing with Office 365 email signatures.
HTML5 has deprecated a few of the older ways of showing media as well as offering up a new way to create games and animations. Audio, video, and canvas are just a few of the adjustments made between XHTML and HTML5. As we learned in our last micr…
Learn how to create flexible layouts using relative units in CSS.  New relative units added in CSS3 include vw(viewports width), vh(viewports height), vmin(minimum of viewports height and width), and vmax (maximum of viewports height and width).

895 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

11 Experts available now in Live!

Get 1:1 Help Now