好的,我将 Zynga Scroller 功能与 KineticJS 框架集成以获得我想要的。
代码在行动
让我们一步一步看一下代码,它是我在网上找到并自己编写的东西的合并。
首先,我们使用 KineticJS 生成画布:
var width = 700;
var height = 700;
var stage = new Kinetic.Stage({
container: 'container',
width: width,
height: height
});
var layer = new Kinetic.Layer({});
stage.add(layer);
/* I skipped some circle generation code. */
然后,我们定义一些在图层上拖放东西时触发的事件。我们将使用这些来填充一个名为 的全局变量somethingIsBeingDraggedInKinetic
。我们将在 Zynga Scroller 的平移代码中使用此变量,因此当您拖动 KineticJS 形状时,整个舞台不会四处移动。
var somethingIsBeingDraggedInKinetic = false;
layer.on('dragstart', function(evt) {
// get the thing that is being dragged
var thing = evt.targetNode;
if( thing )
somethingIsBeingDraggedInKinetic = true;
});
layer.on('dragend', function(evt) {
// get the thing that is being dragged
var thing = evt.targetNode;
if( thing )
somethingIsBeingDraggedInKinetic = false;
});
接下来是 Zynga Scroller 初始化代码。Zynga Scroller 代码处理输入和转换,然后将三个值传递给渲染函数top
:left
和zoom
. 这些值非常适合传递给 KineticJS 框架:
// Canvas renderer
var render = function(left, top, zoom) {
// Constrain the stage from going too far to the right
if( (left + (width / zoom)) > width )
left = width - (width / zoom );
// Constrain the stage from going too far to the left
if( (top + (height / zoom)) > height )
top = height - (height / zoom );
stage.setOffset(left, top);
stage.setScale(zoom);
stage.draw();
};
// Initialize Scroller
this.scroller = new Scroller(render, {
zooming: true,
animating: false,
bouncing: false,
locking: false,
minZoom: 1
});
之后,我们需要正确定位 Zynga Scroller。我承认这部分对我来说有点黑魔法。我从“asset/ui.js”文件中复制了其余的代码。
var container = document.getElementById("container");
var rect = container.getBoundingClientRect();
scroller.setPosition(rect.left + container.clientLeft, rect.top + container.clientTop);
scroller.setDimensions(700, 700, width, height);
最后,我也复制了平移代码,并添加了一些代码来检查 KineticJS 框架是否正在移动某些东西:
var mousedown = false;
container.addEventListener("mousedown", function(e) {
if (e.target.tagName.match(/input|textarea|select/i)) {
return;
}
scroller.doTouchStart([{
pageX: e.pageX,
pageY: e.pageY
}], e.timeStamp);
mousedown = true;
}, false);
document.addEventListener("mousemove", function(e) {
if (somethingIsBeingDraggedInKinetic)
return;
if (!mousedown) {
return;
}
scroller.doTouchMove([{
pageX: e.pageX,
pageY: e.pageY
}], e.timeStamp);
mousedown = true;
}, false);
document.addEventListener("mouseup", function(e) {
if (!mousedown) {
return;
}
scroller.doTouchEnd(e.timeStamp);
mousedown = false;
}, false);
哦,还有缩放处理程序。
container.addEventListener(navigator.userAgent.indexOf("Firefox") > -1 ? "DOMMouseScroll" : "mousewheel", function(e) {
scroller.doMouseZoom(e.detail ? (e.detail * -120) : e.wheelDelta, e.timeStamp, e.pageX, e.pageY);
}, false);
这是可缩放地图的完美基础!