...

View Full Version : Event listener problem on canvas



jason_moutia
09-25-2011, 03:10 AM
I'm trying to simulate a textfield on a canvas; that is when clicking on the text box a cursor appears and blink. My problem here is when I create more than one object, the event listener will work only on the last object created.

Here is my code:
Javascript

var canvas;
var ctx;
var MousePosX;
var MousePosY;
var Cursor_Width = 1;
var Cursor_Height = 21;
var Height = 27;
var LapseTime = 800;

function init(CanvasName) {
canvas = document.getElementById(CanvasName);
ctx = canvas.getContext("2d");
}

/*
Create Textfiled
*/
function Textfield(x, y, w) {
Textfield.prototype.x = x;
Textfield.prototype.y = y;
Textfield.prototype.w = w;
Textfield.prototype.Cursor_PosX = x + 3;
Textfield.prototype.Cursor_PosY = y + 3;

// draw rectangle
ctx.beginPath();
ctx.rect(this.x, this.y, this.w, Height);
ctx.closePath();
ctx.stroke();

// listen for mouse click event
canvas.addEventListener("mousedown", function(evt) {
// calculate mouse coordination on canvas
MousePosX = evt.clientX - canvas.offsetLeft;
MousePosY = evt.clientY - canvas.offsetTop;
// if mouse coordination is within texfield display cursor
if((MousePosX > Textfield.prototype.x && MousePosX < (Textfield.prototype.x + Textfield.prototype.w)) && (MousePosY > Textfield.prototype.y && MousePosY < (Textfield.prototype.y + Height))) {
Textfield.prototype.cursor();
}
});
}

/*
Cursor for textfield
*/
Textfield.prototype.cursor = function() {
// alert("good");
ctx.beginPath();
ctx.strokeStyle = "black";
ctx.rect(this.Cursor_PosX, this.Cursor_PosY, Cursor_Width, Cursor_Height);
ctx.closePath();
ctx.stroke();
setTimeout("Textfield.prototype.animate_cursor()", LapseTime);
};

/*
Change color of cursor to white to make blinking effect
*/
Textfield.prototype.animate_cursor = function() {
ctx.strokeStyle = "white";
ctx.stroke();
setTimeout("Textfield.prototype.cursor()", LapseTime);
};

HTML

<!DOCTYPE HTML>
<html>
<head>
<style>
#MyCanvas {
border: 1px solid #000000;
}
</style>
<script src="widgets1.js"></script>
<script>
window.onload = function () {
init('MyCanvas');
var tf1 = new Textfield(10.5, 10.5, 150);
var tf2 = new Textfield(10.5, 50.5, 150);
};
</script>
</head>
<body>
<br /><br /><br />
<center>
<canvas id="MyCanvas" width="700" height="500">
</canvas>
</center>
</body>
</html>

What i want to achieve here is have my event listener on any textfield created on the canvas.

DaveyErwin
09-25-2011, 03:13 PM
The problem you describe is because
MousePosX and MousePosY are global.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum