I want to draw all the points a user clicks on the canvas until the user clicks on the first clicked. I am able to store them on a hidden input, but I can't get them to draw/show ("ctx.fillRect(pos_x, pos_y, 1, 1);") on screen properly. What is my code missing? I only see the first point and it is not even on the place I clicked (viewing using IE Edge). Eventually I would like to add the lines drawn by the points.
Also, as an extra, could someone please help me determine if the click was within the canvas for the time the code is detecting the context menu?
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var c;
var ctx;
function wireUp()
{
// Initiate context. Do only once
c = document.getElementById('imgContainer');
ctx = c.getContext('2d');
// Store points
keepPoints('hiddenMap');
// Override context when user has clicked within the canvas
window.oncontextmenu = function ()
{
// TO DO: Detect click was within canvas area
clearMap('imgContainer', 'hiddenMap');
return false; // cancel default menu
}
document.getElementById('imgContainer').onclick = function (e) {
// Detect RMB. See: http://stackoverflow.com/questions/2405771/is-right-click-a-javascript-event
var isRightMB;
e = e || window.event;
if ("which" in e) // Gecko (Firefox), WebKit (Safari/Chrome) & Opera
isRightMB = e.which == 3;
else if ("button" in e) // IE, Opera
isRightMB = e.button == 2;
if(!isRightMB)
{
pointDetected('imgContainer', 'hiddenMap', e);
}
else
{ // Clear points, drawn and on map
alert("RMB");
clearMap('imgContainer', 'hiddenMap');
}
};
}
function clearMap(container, map)
{
// Clear drawn points
var canvas = document.getElementById(container);
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Clear map
var hMap = document.getElementById(map);
hMap.value = "";
}
function pointDetected(container, map, event)
{
//alert("Oh my! " + container);
pos_x = event.offsetX?(event.offsetX):event.pageX-document.getElementById(container).offsetLeft;
pos_y = event.offsetY?(event.offsetY):event.pageY-document.getElementById(container).offsetTop;
//alert(pos_x + ", " + pos_y);
var hMap = document.getElementById(map);
if(hMap.value) // Check if the map has already points and append with comma
{
hMap.value = hMap.value + "; " + pos_x + ", " + pos_y;
}
else
{
hMap.value = pos_x + ", " + pos_y;
}
alert(hMap.value);
// Draw a point where clicked
ctx.fillRect(pos_x, pos_y, 1, 1);
}
function keepPoints(container)
{
// Stores all the points that the user has selected
var hidden = document.createElement("input");
var typeAtt = document.createAttribute("type");
typeAtt.value = "hidden";
hidden.setAttributeNode(typeAtt);
hidden.id = container;
document.body.appendChild(hidden);
}
</script>
</head>
<body onload="wireUp();">
<canvas style="background:url('untitled.png');width:819px;height:460px;border-style:solid;" id="imgContainer">
</canvas>
</body>