Click here to Skip to main content
15,917,174 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Below is JavaScript which creates a polygon or line depending on the radio button selected.

I want to convert my code as such that instead of radio button, I can execute function using simple input button. Do I have to write seperate event listeners for both buttons?

If so, how will I call them in HTML? Or will one event listener do just fine? How will the events be handled then?

function onPageLoaded()
{
canvas.addEventListener("click", onCanvasClick, false);
setInterval(updateScreen, 100);
}

function onCanvasClick(e)
{
var x = e.clientX-canvas.offsetLeft;
var y = e.clientY-canvas.offsetTop;

switch (byId('shapeType').value)
{
case 'poly': polyClick(x,y);
break;
case 'line': lineClick(x,y);
break;
}
}
Instead of this

<select id='shapeType'>
<option value="poly" selected>Polygon</option>
<option value="line">Line</option>
</select>
I want to use this

<input type="button" value="Add polygon">
<input type="button" value="Add line">
For full code u can see the solution of this thread http://www.codeproject.com/Answers/693319/unable-to-draw-more-then-1-shape-on-html5-canvas#answer1
Posted

well here is the solution. Add a common class to the buttons and then write up the code for the same.

HTML

<input type="button" value="Add polygon" class="draw" data-type="poly">
<input type="button" value="Add line" class="draw" data-type="line">
JS

function onPageLoaded() {
var buttons = document.getElementsByClassName('draw');
for(var i=0;i < buttons.length; i++) {
buttons[i].addEventListener("click", onButtonClick, false);
}
setInterval(updateScreen, 100);
}

function onCanvasClick(e) {
var x = e.clientX-canvas.offsetLeft;
var y = e.clientY-canvas.offsetTop;

switch (this.getAttribute("data-type")) {
case 'poly': polyClick(x,y);
break;
case 'line': lineClick(x,y);
break;
}
}
 
Share this answer
 
Modify the code in unable to draw more then 1 shape on html5 canvas[^] as follows:

XML
var shapeType = 'poly';

.....

function onCanvasClick(e)
{
...
    //switch (byId('shapeType').value)
    switch (shapeType)
...
}

.....

// called whenever the screen needs updating
function updateScreen()
{
...
    //switch (byId('shapeType').value)
    switch (shapeType)
...

}

....

<input type="button" value="Add polygon" onclick="shapeType='poly';">
<input type="button"  value="Add line"  onclick="shapeType='line';">
<!--
<select id='shapeType'>
    <option value="poly" selected>Polygon</option>
    <option value="line">Line</option>
</select>
-->
 
Share this answer
 
v4

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900