【问题标题】:HTML / D3.js - how to zoom from the mouse cursor rather than top-left cornerHTML / D3.js - 如何从鼠标光标而不是左上角缩放
【发布时间】:2018-10-30 01:57:10
【问题描述】:

我有一张这样的图片(demo),可以通过鼠标滚轮向上或向下缩放。但它只是可以从左上角缩放...

如何尝试使其从鼠标光标点缩放(例如 example)。 另外,我需要有图片边界,而不是像这个例子是无限的。感谢您的任何回答或建议。

HTML、CSS

//Html
<div id="picture"></div>

//css
#picture {
  width: 340px;
  height: 150px;
  overflow: auto;
}

JavaScript

createSVG = function () {

  var svg = d3.select('#picture')
  .append('svg')
  .attr('width', rw)
  .attr('height', rh)
  .style('border', '1px solid #000');

  svg.append('svg:image')
    .attr('xlink:href', 'http://www.iconpng.com/png/beautiful_flat_color/computer.png')
    .attr('width', rw)
    .attr('height', rh);
}


//Init (Original size)
var Picture_w = 340;
var Picture_h = 150;
value = 96;                      //(scaling ratio)
rw = Picture_w * value / 100;
rh = Picture_h * value / 100;

createSVG();

// When change scaling ratio, RE createSVG();
changeSize = function () {
  d3.select('svg').remove();

  rw = Picture_w * value / 100;
  rh = Picture_h * value / 100;

  createSVG();
};


//mousewheel (Chrome or IE)
$('#picture').on('mousewheel DOMMouseScroll', function (e) {
  e.preventDefault();
  if (e.type == 'mousewheel') {
    if (e.originalEvent.wheelDelta > 0) {

      value += 2;
      if (value > 500) {
        value = 500;
      }
      changeSize();
      // console.log(e.originalEvent.wheelDelta);
    }
    else {

      value -= 2;
      if (value < 5) {
        value = 5;
      }
      changeSize();
      // console.log("w" + e.originalEvent.wheelDelta);
    }
  }

});

【问题讨论】:

  • 在 createSVG 函数中添加类似的事件处理程序
  • .on("mouseover", changeSize)

标签: javascript html d3.js


【解决方案1】:

我不确定你在看什么,但是我用你的代码创建了一个D3 zoom 并使用Mike Bostock’s Block 方法实现了缩放。

想法是创建缩放行为并将其应用于指定的选择/元素。

var parent = d3.select("#picture");

var zoom = d3.zoom()
    .scaleExtent([0.5, 8])
    .on("zoom", zoomed);

parent.call(zoom);

function zoomed() {
  parent.select("svg").attr("transform", d3.event.transform);
}

function reset() {
	parent.transition()
      .duration(750)
      .call(zoom.transform, d3.zoomIdentity);
}
#picture {
  width: 340px;
  height: 150px;
  overflow: auto;
}

.parent {
	border : 1px solid #000;
}
<script src="//d3js.org/d3.v5.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<div id="picture">
	<svg width="330" height="140" class="parent"><g class="image"><image xlink:href="http://www.iconpng.com/png/beautiful_flat_color/computer.png" width="330" height="140" class="pictureWrapper"></image></g></svg>
</div>
<button onclick="reset()">Reset</button>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-19
    • 2012-07-15
    • 1970-01-01
    • 2011-07-08
    • 2015-04-27
    • 2016-04-20
    • 2015-10-07
    • 2018-12-08
    相关资源
    最近更新 更多