我有2幅画布: -
<canvas id="myCanvas" width="915" height="650" style="border: 2px double #000000;"></canvas>
<canvas id="pharmacy" width="915" height ="320" style ="border:2px double #000000;"></canvas>
它们是单独的画布,位于同一个aspx页面上。
这个想法是让它们都代表一个时间轴。即它们都可以从左向右滚动,反之亦然。
我刚刚创建了第一个画布,最近决定实现第二个画布。
当我复制粘贴第二个画布中的原始代码以模拟滚动部分时,我发现在实践中,当我滚动时,只有原始画布会滚动而新画布不滚动。
如果我注释掉原始画布的代码,那么新画布会滚动。
这让我想到,我试图实现的基于事件的滚动在其命名约定中存在某种形式的缺陷。 (因为鼠标单击表示为事件,然后允许拖动;我的代码只记录原始画布的拖动事件而不是新画布。)
如果有人能看一下代码并让我知道我哪里出错了,我将不胜感激?
目标: - 点击任一画布,拖动鼠标,两个画布同时滚动。
第一幅画布: -
// when mouse is clicked on canvas
window.onmousedown = function (e) {
var evt = e || event;
// dragging is set to true.
dragging = true;
lastX = evt.offsetX;
}
// when mouse is clicked again and the canvas is deselected
window.onmouseup = function () {
// dragging is set to false.
dragging = false;
}
// when mouse is dragging the canvas sideways
can.onmousemove = function (e) {
var evt = e || event;
if (dragging) {
var delta = evt.offsetX - lastX;
translated += delta;
//console.log(translated);
ctx.restore();
ctx.clearRect(0, 0, 930, 900);
ctx.save();
ctx.translate(translated, 0);
lastX = evt.offsetX;
timeline();
}
}
第二幅画布: -
// when mouse is clicked on canvas
window.onmousedown = function (e) {
var evt = e || event;
// dragging is set to true.
dragging = true;
lastX = evt.offsetX;
}
// when mouse is clicked again and the canvas is deselected
window.onmouseup = function () {
// dragging is set to false.
dragging = false;
}
// when mouse is dragging the canvas sideways
can1.onmousemove = function (e) {
var evt = e || event;
if (dragging) {
var delta = evt.offsetX - lastX;
translated += delta;
//console.log(translated);
ctx1.restore();
ctx1.clearRect(0, 0, 915, 600);
ctx1.save();
ctx1.translate(translated, 0);
lastX = evt.offsetX;
pharm_line();
}
}
现在我希望can和can1在任何mousedown和mousemove事件上同步移动,并在鼠标启动时停止。
答案 0 :(得分:1)
您可以使用常用的鼠标处理程序来同时滚动两个画布。
请参阅下面的window.onmousemove
,它会使两个画布保持翻译同步。
// when mouse is clicked on canvas
window.onmousedown = function (e) {
var evt = e || event;
// dragging is set to true.
dragging = true;
lastX = evt.offsetX;
}
// when mouse is clicked again and the canvas is deselected
window.onmouseup = function (e) {
// dragging is set to false.
dragging = false;
}
window.onmousemove = function(e) {
var evt = e || event;
if (dragging) {
var delta = evt.offsetX - lastX;
translated += delta;
move(ctx,930,900);
move(ctx1,915,600);
lastX = evt.offsetX;
timeline();
pharm_line();
}
}
// common code used to service either canvas
function move(context,width,height){
context.restore();
context.clearRect(0, 0, width, height);
context.save();
context.translate(translated, 0);
}