在KineticJS中缩放和平移 [英] Zoom and Pan in KineticJS

查看:170
本文介绍了在KineticJS中缩放和平移的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法可以使用KineticJS在画布上缩放和平移?我发现这个图书馆 kineticjs-viewport ,但只是想知道是否还有其他办法实现这一点,因为这个库似乎使用了这么多额外的库,并且不确定哪些是完成工作所必需的。

Is there a way one could zoom and pan on a canvas using KineticJS? I found this library kineticjs-viewport, but just wondering if there is any other way of achieving this because this library seems to be using so many extra libraries and am not sure which ones are absolutely necessary to get the job done.

或者,我甚至愿意接受围绕感兴趣区域绘制矩形并放大到该特定区域的想法。关于如何实现这一点的任何想法?一个JSFiddle的例子真棒!

Alternatively, I am even open to the idea of drawing a rectangle around the region of interest and zooming into that one particular area. Any ideas on how to achieve this? A JSFiddle example would be awesome!

推荐答案

你可以简单地添加 .setDraggable(draggable)到一个图层,只要光标下有一个对象,你就可以拖动它。您可以添加一个大的,透明的 rect 来使所有内容都可以拖动。可以通过设置图层的比例来实现缩放。在这个例子中,我通过鼠标滚轮控制它,但它只是一个函数,你传递你想要缩放的数量(正向放大,负向缩小)。以下是代码:

You can simply add .setDraggable("draggable") to a layer and you will be able to drag it as long as there is an object under the cursor. You could add a large, transparent rect to make everything draggable. The zoom can be achieved by setting the scale of the layer. In this example I'm controlling it though the mousewheel, but it's simply a function where you pass the amount you want to zoom (positive to zoom in, negative to zoom out). Here is the code:

var stage = new Kinetic.Stage({
    container: "canvas",
    width: 500,
    height: 500
});

var draggableLayer = new Kinetic.Layer();
draggableLayer.setDraggable("draggable");

//a large transparent background to make everything draggable
var background = new Kinetic.Rect({
    x: -1000,
    y: -1000,
    width: 2000,
    height: 2000,
    fill: "#000000",
    opacity: 0
});

draggableLayer.add(background);


//don't mind this, just to create fake elements
var addCircle = function(x, y, r){
  draggableLayer.add(new Kinetic.Circle({
        x: x*700,
        y: y*700,
        radius: r*20,
        fill: "rgb("+ parseInt(255*r) +",0,0)"
    })
  );
}

var circles = 300
while (circles) {
  addCircle(Math.random(),Math.random(), Math.random())
  circles--;
}

var zoom = function(e) {
  var zoomAmount = e.wheelDeltaY*0.001;
  draggableLayer.setScale(draggableLayer.getScale().x+zoomAmount)
  draggableLayer.draw();
}

document.addEventListener("mousewheel", zoom, false)

stage.add(draggableLayer)

http://jsfiddle.net/zAUYd/

这篇关于在KineticJS中缩放和平移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆