To integrate D3 Band zoom in D3 heatmap

2019-06-13 15:57发布

问题:

Here I want to integrate D3 Band zoom in D3 Heatmap with resettable zoom. The red band appears while dragging, but it didn't zoom. I think, there some issue in zoom function, but i couldn't track it yet. Please check out my fiddle.

Zoom function:

function zoom() {

    //recalculate domains
  if(zoomArea.x1 > zoomArea.x2) {
      x.domain([zoomArea.x2, zoomArea.x1]);
    } else {
      x.domain([zoomArea.x1, zoomArea.x2]);
    }

    if(zoomArea.y1 > zoomArea.y2) {
      y.domain([zoomArea.y2, zoomArea.y1]);
    } else {
      y.domain([zoomArea.y1, zoomArea.y2]);
    }

    var t = svg.transition().duration(750);
    t.select(".x.axis").call(scale[X]);
    t.select(".y.axis").call(scale[Y]);
}

Please suggest a method to resolve it. Thank you in advance.

回答1:

Here is a potential canvas-based solution.

You can modify your zoom function to force a redraw using only a sub rectangle of the image with

context.drawImage(image,sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);

Then give sx,sy top-left coordinates of your selection rectangle, and sWidth,sHeight width and size of selection rectangle.

dx,dy,dWidth,dHeight are constant in your case, 0,0,canvasWidth,canvasSize

You will probably need to modify createImageObj to also use drawImage rather than putImage. I am not familiar with canvas so you need to check this point.

Hope this helps.

For reference, MDN docs on drawImage



回答2:

Here is a potential solution.

First, ditch the canvas.

Use the following structure instead :

<svg>
  <g id="x axis">
    // ...
  </g>
  <g id="y axis">
    // ...
  </g>
  <svg id="imageContainer" viewbox="0 0 heatmapDim[0] heatmapDim[1]">
    <image xlink:href="yourHeatmap"/>  	
  </svg>
</svg>

The key here is to use the viewBox attribute of the second <svg> (#imageContainer). This will allow you to define a subwindow on your image

And modify your zoom

function zoom() {
        
    	//recalculate domains
      var x0,x1,y0,y1;
  
      if(zoomArea.x1 > zoomArea.x2) {
          x0 = zoomArea.x2;
          x1 = zoomArea.x1;
        } else {
          x0 = zoomArea.x1;
          x1 = zoomArea.x2;
        }
        
        if(zoomArea.y1 > zoomArea.y2) {
          y0 = zoomArea.y2
          y1 = zoomArea.y1;
        } else {
          y0 = zoomArea.y1;
          y1 = zoomArea.y2;
        }
        
        
        d3.select("#imageContainer").attr("viewBox",x0 + " " + y0 + " " + x1 + " " + y1);
       
  }

That should do the trick, haven't tested it thought, your fiddle is quite large and that doesn't help.