У меня есть три события javascript - mouseup, mousedown и mousemove. Для каждого события вызывается отдельная функция. Я хочу, чтобы эти три функции использовали одну и ту же переменную, которой присваивается начальное значение вне этих функций.
Можно ли это сделать?
Сарфраз попросил код и вот он:
if(window.addEventListener) {
window.addEventListener('load', function () {
var canvas, context;
// Initialization sequence.
var z=false;
function init () {
// Find the canvas element.
canvas = document.getElementById('imageView');
if (!canvas) {
alert('Error: I cannot find the canvas element!');
return;
}
if (!canvas.getContext) {
alert('Error: no canvas.getContext!');
return;
}
// Get the 2D canvas context.
context = canvas.getContext('2d');
if (!context) {
alert('Error: failed to getContext!');
return;
}
// Attach the mousemove event handler.
canvas.addEventListener('mousedown',ev_mousedown,false);
canvas.addEventListener('mouseup',ev_mouseup,false);
canvas.addEventListener('mousemove', ev_mousemove, false);
}
//The mouseup
function ev_mouseup(ev)
{
z=false;
}
//The mousedown
function ev_mousedown(ev)
{
z=true;
}
// The mousemove event handler.
var started = false;
function ev_mousemove (ev) {
var x, y;
// Get the mouse position relative to the canvas element.
if (ev.layerX || ev.layerX == 0) { // Firefox
x = ev.layerX;
y = ev.layerY;
} else if (ev.offsetX || ev.offsetX == 0) { // Opera
x = ev.offsetX;
y = ev.offsetY;
}
// The event handler works like a drawing pencil which tracks the mouse
// movements. We start drawing a path made up of lines.
if (!started) {
if(z){
context.beginPath();
context.moveTo(x, y);
started = true;
}
} else {
context.lineTo(x, y);
context.stroke();
}
}
init();
}, false); }