Solved

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

Posted on 2015-02-09
5
162 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:Tom Knowlton
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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:Tom 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:Tom Knowlton
ID: 40600945
Okay.  So it is kind of like "close the shape"
0

Featured Post

Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

Question has a verified solution.

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

Suggested Solutions

Building a website can seem like a daunting task to the uninitiated but it really only requires knowledge of two basic languages: HTML and CSS.
Finding original email is quite difficult due to their duplicates. From this article, you will come to know why multiple duplicates of same emails appear and how to delete duplicate emails from Outlook securely and instantly while vital emails remai…
In this tutorial viewers will learn how to style transparent/translucent elements using alpha transparency in CSS Start with a normal styled element, such as a div.: Define its "background-color" property as "rgba (255, 255, 255, .5): The numbers in…
The viewer will learn the benefit of using external CSS files and the relationship between class and ID selectors. Create your external css file by saving it as style.css then set up your style tags: (CODE) Reference the nav tag and set your prop…

710 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