If there is no div element surrounding the canvas div then I was able to get the mouse position.
http://hpportfolio.zymichost.com/Portfolio/portfolio_html5/canvas4.html
- Code: Select all
<body>
<div id="canvasDiv"></div>
<script type="text/javascript">
$(document).ready(function() {
prepareCanvas(1);
});
</script>
</body>
- Code: Select all
var canvas;
var context;
var canvasWidth = 490;
var canvasHeight = 220;
var coordinateDisplay;
var tmp = 0;
function prepareCanvas(tmp)
{
// Create the canvas (Neccessary for IE because it doesn't know what a canvas element is)
var canvasDiv = document.getElementById('canvasDiv');
canvas = document.createElement('canvas');
canvas.setAttribute('width', canvasWidth);
canvas.setAttribute('height', canvasHeight);
canvas.setAttribute('id', 'canvas');
canvasDiv.appendChild(canvas);
if(typeof G_vmlCanvasManager != 'undefined') { //since canvas element is dynamically it will not have the getContext method
//added to the element. To get it working you need to call initElement on the G_vmlCanvasManager object.
canvas = G_vmlCanvasManager.initElement(canvas);
}
context = canvas.getContext("2d");
// Add mouse events
// ----------------
if (tmp == 1){
tmpMouseMove();
} else{
$('#canvas').mousemove(function(e){
alert("I'm working");
});
}
}
function tmpMouseMove(){
$('#canvas').mousemove(function(e){
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
var coordinateDisplay = "x=" + x + ", y=" + y;
writeCoordinateDisplay(coordinateDisplay);
});
}
function writeCoordinateDisplay(coordinateDisplay) {
clearCanvas();
context.font="18pt Calibri";
context.fillText(coordinateDisplay, 200, 100);
}
function clearCanvas() {
context.clearRect(0,0,canvas.width, canvas.height);
context.beginPath();
}
Canvas enclosed in div
- Code: Select all
<div id="wrapper">
<div class="project" id="">
<div class="primary">
<span class="section_title">Tracking Mouse Position</span>
<div id="canvasDiv"></div>
<script type="text/javascript">
$(document).ready(function() {
prepareCanvas(1);
});
</script>
</div> <!-- end primary-->
<div class="secondary">
<div class="thumb">
</div> <!-- end thumb-->
</div> <!-- end secondary-->
</div> <!--end -->
</div><!-- End wrapper -->
But when I try to enclose canvas inside another div element, then I was not able to get the mouse co-ordinates.
http://hpportfolio.zymichost.com/Portfolio/portfolio_html5/canvas2.html
Can anybody pls help me with this?? Thanks