The following code is working properly in other browsers except IE. My code is:
<script lang="javascript" type="text/javascript">
alert("fdgdfgdfg");
var canvas;
var ctx;
var canX;
var canY;
var rltvX;
var rltvY;
var x = "black";
var flag = false;
var w, h;
function init() {
alert("aaaaaaaaaaa");
alert("bbbbbbbbbbb");
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
w = canvas.width;
h = canvas.height;
canvas.addEventListener("mousemove", function(e) {findxy('move', e);}, false);
canvas.addEventListener("mousedown", function(e) {findxy('down', e);}, false);
canvas.addEventListener("mouseup", function(e) {findxy('up', e);}, false);
canvas.addEventListener("mouseout", function(e) {findxy('out', e);}, false);
canvas.addEventListener("touchstart", touchDown, false);
canvas.addEventListener("touchmove", move, true);
canvas.addEventListener("touchend", touchUp, false);
document.body.addEventListener("mouseup", mouseUp, false);
document.body.addEventListener("touchcancel", touchUp, false);
}
function findxy(res, e) {
if (res == 'down') {
canX = e.clientX - canvas.offsetLeft-5;
canY = e.clientY - canvas.offsetTop-25;
flag = true;
dot_flag = true;
if (dot_flag) {
ctx.beginPath();
ctx.fillStyle = x;
ctx.fillRect(canX, canY, 2, 2);
ctx.closePath();
dot_flag = false;
}
}
if (res == 'up' || res == "out") {
flag = false;
}
if (res == 'move') {
if (flag) {
rltvX = canX;
rltvY = canY;
canX = e.clientX - canvas.offsetLeft-5;
canY = e.clientY - canvas.offsetTop-25;
ctx.beginPath();
ctx.moveTo(rltvX, rltvY);
ctx.lineTo(canX, canY);
ctx.strokeStyle = x;
ctx.lineWidth = 2;
ctx.stroke();
ctx.closePath();
}
}
}
function touchDown(e) {
if (!e)
var e = event;
e.preventDefault();
canX = e.targetTouches[0].pageX - canvas.offsetLeft-5;
canY = e.targetTouches[0].pageY - canvas.offsetTop-25;
ctx.beginPath();
ctx.fillStyle = x;
ctx.fillRect(canX, canY, 2, 2);
ctx.closePath();
}
function move(e) {
if (!e)
var e = event;
e.preventDefault();
rltvX = canX;
rltvY = canY;
canX = e.targetTouches[0].pageX - canvas.offsetLeft-5;
canY = e.targetTouches[0].pageY - canvas.offsetTop-25;
ctx.beginPath();
ctx.strokeStyle = x;
ctx.lineWidth = 2;
ctx.moveTo(rltvX, rltvY);
ctx.lineTo(canX, canY);
ctx.stroke();
}
</script>
The error is, the object ‘canvas’ does not support the method addEventListener(). This is working properly in all browsers except IE. is there any alternative?
If you are using IE8 you should use the
attachEvent()method instead ofaddEventListener(). This means you have to check first which browser the user has, then call the correct method on the element.EDIT for how to check which method to use:
Where
elis your DOM element.