gpt4 book ai didi

javascript - 请解释此代码段

转载 作者:可可西里 更新时间:2023-11-01 12:53:41 25 4
gpt4 key购买 nike

我在浏览 html5 canvas 示例时遇到了这段代码。我已经粘贴了代码,并在我有疑问的地方给出了评论。

if(window.addEventListener) {

window.addEventListener('load', function () {
var canvas, context, tool;

function init () {
canvas = document.getElementById('imageView');
if (!canvas) {
alert('Error: I cannot find the canvas element!');
return;
}

if (!canvas.getContext) {
alert('Error: no canvas.getContext!');
return;
}

context = canvas.getContext('2d');
if (!context) {
alert('Error: failed to getContext!');
return;
}

tool = new tool_pencil();

canvas.addEventListener('mousedown', ev_canvas, false);
canvas.addEventListener('mousemove', ev_canvas, false);
canvas.addEventListener('mouseup', ev_canvas, false);
}

function tool_pencil () {
var tool = this;
this.started = false;


this.mousedown = function (ev) {
context.beginPath();
context.moveTo(ev._x, ev._y);
tool.started = true;
};

this.mousemove = function (ev) {
if (tool.started) {
context.lineTo(ev._x, ev._y);
context.stroke();
}
};

this.mouseup = function (ev) {
if (tool.started) {
tool.mousemove(ev);
tool.started = false;
}
};
}

function ev_canvas (ev) {
if (ev.layerX || ev.layerX == 0) {
ev._x = ev.layerX;
ev._y = ev.layerY;
} else if (ev.offsetX || ev.offsetX == 0) {
ev._x = ev.offsetX;
ev._y = ev.offsetY;
}

//Please explain the follwing set of line
var func = tool[ev.type];
if (func) {
func(ev);
}
}

init();

}, false); }

最佳答案

结合其他答案,它正在做的是将所有回调放在一个对象中。结果是functool.onmousedown, tool.onmouseup

关于javascript - 请解释此代码段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4130668/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com