I am currently working on a project where I need to create a canvas-like table with around 10,000 cells. The goal is to allow users to draw on this canvas by moving their mouse over it while holding down specific keys (e.g. ctrl for blue, shift for red).
While I have successfully generated the HTML code for the table, I am facing an issue with the functionality. It seems that instead of filling in the cells with color, my script is trying to select them.
Below is a preview of what I am experiencing:
HTML:
<html>
<head>
<meta charset="utf-8">
<title>Drawing Program</title>
<h1>Drawing Demonstration</h1>
<link rel = "stylesheet" type = "text/css" href = "style.css">
<script src = "draw.js"></script>
</head>
<body>
<table id = "canvas">
<caption>Hold Ctrl (or Control) to draw in blue.
Hold Shift to draw in red.</caption>
<tbody id = "tablebody"></tbody>
</table>
</body>
</html>
CSS:
table{
width: 400px;
height: 400px;
border-collapse: collapse;
}
td {
width: 4px;
height: 4px;
border-collapse: collapse;
}
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 );
}
tbody.appendChild( row );
}
document.getElementById( "canvas" ).addEventListener( "mousemove", processMouseMove, false );
}
function processMouseMove( e )
{
if( e.target.tagName.toLowerCase() == "td" )
{
if( e.ctrlKey )
{
e.target.setAttribute( "class", "blue" );
}
if ( e.shiftKey )
{
e.target.setAttribute( "class", "red" );
}
}
}
window.addEventListener( "load", createCanvas, false );