Chiranjeevi Aripaka

Chiranjeevi Aripaka

  • NA
  • 133
  • 304.1k

how to clear drawing in canvas using button

Jul 21 2017 3:36 AM
Dear collegues ,
 
Please help me in deleting the images drawn in html canvas with the help of a clear button . when we click on the the button entire canvas area should be cleaned for redrawing.
 
Below is the code i have used:
 
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
#canvas { width: 400px;
border: 1px solid #999999;
border-collapse: collapse }
td { width: 4px; height: 4px; margin: 0px; padding: 0px; }
.blue { background-color: blue; }
.red { background-color: red; }
.white { background-color: white; }
#buttons {
position: absolute;
top: 5px;
left: 10px;
}
#buttons > input {
padding: 10px;
display: block;
margin-top: 5px;
}
</style>
<script type="text/javascript">
function createCanvas() {
var side = 100;
var tbody = document.getElementById("tablebody");
for (var i = 0; i < side; ++i) {
var row = document.createElement("tr");
for (var j = 0; j < side; ++j) {
var cell = document.createElement("td");
row.appendChild(cell);
} // end for
tbody.appendChild(row);
} // end for
// register mousemove listener for the table
document.getElementById("canvas").addEventListener(
"mousemove", processMouseMove, false);
} // end function createCanvas
// processes the onmousemove event
function processMouseMove(e) {
if (e.target.tagName.toLowerCase() == "td") {
// turn the cell blue if the Ctrl key is pressed
if (e.ctrlKey) {
e.target.setAttribute("class", "blue");
} // end if
// turn the cell red if the Shift key is pressed
if (e.shiftKey) {
e.target.setAttribute("class", "red");
} // end if
if (e.altKey) {
e.target.setAttribute("class", "white");
}
} // end if
} // end function processMouseMove
window.addEventListener("load", createCanvas, false);
document.getElementById('clear').addEventListener('click', function()
{context.clearRect(0, 0, canvas.width, canvas.height);}, false);
</script>
</head>
<body>
<center>
<table id = "canvas">
<caption> Press control_button to draw in blue color
Hold Shift_button to draw red and press Alt_button to erase.</caption>
<tbody id = "tablebody"></tbody>
</table>
<button onclick="clearall()"> clear </button>
</center>
</body>
</html>
 

Answers (1)