以下代码在IE以外的其他浏览器中正常运行。我的代码是:
<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>
错误是,对象'canvas'不支持方法addEventListener()
。这在除IE之外的所有浏览器中都能正常工作。还有其他选择吗?
答案 0 :(得分:3)
如果您使用的是IE8,则应使用attachEvent()
方法而不是addEventListener()
。这意味着您必须首先检查用户具有哪个浏览器,然后在元素上调用正确的方法。
编辑如何检查使用哪种方法:
if (el.addEventListener){
el.addEventListener(...);
} else if (el.attachEvent){
el.attachEvent(...);
}
el
是你的DOM元素。