本文介绍了触发缩放事件(或模拟缩放事件)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我用鼠标缩放时,将执行myZoom附带的以下功能:

When I zoom with the mouse, the following function attached to myZoom will be executed:

myZoom.on('zoom', function() {

    someElement.attr('transform', 'translate(' + d3.event.translate[0] + ',' + d3.event.translate[1] + ') scale(' + d3.event.scale + ')');

....
// redraw axes, which should stay where they are at.
....

}

要模拟不使用鼠标或其他定点设备的缩放,我只需更改上面属性"transform"的值即可.容易.

To simulate zoom without mouse or some other pointing device, I can just change the value of the attribute 'transform' above. Easy.

但是这个函数的问题是我实际上重绘了轴,轴的比例会自动重新计算.请参阅d3中的此官方文档:

But problem is in this function I actually redraw axes, whose scale is automatically recalculated. Refer to this official documentation from d3:

我需要以编程方式进行缩放(也许使用缩放按钮).如何触发缩放事件,以便自动重新计算轴的比例?

I need to zoom programmatically (maybe with zoom button). How can I fire zoom event, so that scale of my axes is automatically recalculated?

推荐答案

程序缩放似乎在D3库中是一项艰巨的任务,因为D3缩放与鼠标事件紧密相关.程序化缩放的常见实例是使用滑块控件进行放大或缩小.令人惊讶的是,我找不到一个如何使用滑块控件使D3缩放工作的示例.经过一些时间和精力,我开发了这个工作演示,可以在这里找到 D3SliderZoom .关键是改变< g"的变换属性.嵌入在< svg>"中的SVGElement元素使用滑块抛出的比例值.

Programmatic zoom seems to be a daunting task in the D3 library because the D3 zooming is closely tied to the mouse events. A common instance of programmatic zooming is zooming in or out with a slider control. Surprisingly, I couldn't find a single working example of how to make D3 zooming work with a slider control. After investing some time and effort I developed this working demo which can be found here D3SliderZoom. The key point is to change the transform attribute of a "<g>" SVGElement embedded in an "<svg>" element using the scale value thrown by the slider.

function zoomWithSlider(scale) {
    var svg = d3.select("body").select("svg");
    var container = svg.select("g");
    var h = svg.attr("height"), w = svg.attr("width");

    // Note: works only on the <g> element and not on the <svg> element
    // which is a common mistake
    container.attr("transform",
            "translate(" + w/2 + ", " + h/2 + ") " +
            "scale(" + scale + ") " +
            "translate(" + (-w/2) + ", " + (-h/2) + ")");

}

然后必须从滑块的change事件中调用此方法,如下所示.

This method then has to be invoked from the change event of the slider as shown below.

$(function() {
$( "#slider-vertical" ).slider({
    orientation: "vertical",
    range: "min",
    min: 1000,
    max: 10000,
    value: 1000,
    slide: function( event, ui ) {
        zoomWithSlider(ui.value/1000);
    }
});

});

此解决方案比生成伪鼠标滚动事件要优雅得多.

This solution is much more elegant than generating pseudo-mouse scroll event.

这篇关于触发缩放事件(或模拟缩放事件)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 06:16