下面的代码功能类似于 MSpaint 的铅笔工具,下面的代码适用于除 IE 之外的所有浏览器,它在 IE 中没有错误,因为我包含了一个脚本文件以使画布标签在 IE 中运行,在 IE 中绘制手绘线是无法正常工作,因为它在其他浏览器中工作。如果我缓慢移动鼠标,它会工作一段时间,但即使在 IE 中单击并移动鼠标,它也会停止绘制。我应该做出哪些改变?
-init 方法在加载 body 标签时被调用
var canvas;
var ctx;
var canX;
var canY;
var rltvX;
var rltvY;
var x = "black";
var flag = false;
var w, h;
function findxy(res, e)
{
if (res == 'down')
{
canX = e.clientX - canvas.offsetLeft - 10;
canY = e.clientY - canvas.offsetTop - 35;
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;
flag = false;
}
if (res == 'move')
{
if (flag) {
rltvX = canX;
rltvY = canY;
canX = e.clientX - canvas.offsetLeft - 10;
canY = e.clientY - canvas.offsetTop - 35;
ctx.beginPath();
ctx.moveTo(rltvX, rltvY);
ctx.lineTo(canX, canY);
ctx.strokeStyle = x;
ctx.lineWidth = 2;
ctx.stroke();
ctx.closePath();
}
}
}
function init()
{
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
w = canvas.width;
h = canvas.height;
if (canvas.addEventListener)
{
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);
} else {
canvas.attachEvent("onmousemove", function(e) {findxy('move', e);});
canvas.attachEvent("onmousedown", function(e) {findxy('down', e);});
canvas.attachEvent("onmouseup", function(e) {findxy('up', e);});
canvas.attachEvent("onmouseout", function(e) {findxy('out', e);});
}
}