JavaScript画布,图表/图形上两点之间的比例?

JavaScript画布,图表/图形上两点之间的比例?,javascript,charts,Javascript,Charts,因此,我用JavaScript构建了一个小型图形应用程序,以帮助我练习如何使用画布。在过去的10个小时里,我一直试图在X轴上的两个点之间进行缩放,但我一辈子都想不出来。我已经学会了缩放需要翻译>缩放>翻译。当我使用下面的类型代码缩放到最左/最右时,这可以很好地工作 let x = 0; let y = this.getCanvasHeight() / 2; this.getCanvasContext().clearRect(0, 0, this.getCanvas().width, this.

因此,我用JavaScript构建了一个小型图形应用程序,以帮助我练习如何使用画布。在过去的10个小时里,我一直试图在X轴上的两个点之间进行缩放,但我一辈子都想不出来。我已经学会了缩放需要翻译>缩放>翻译。当我使用下面的类型代码缩放到最左/最右时,这可以很好地工作

let x = 0;
let y = this.getCanvasHeight() / 2;

this.getCanvasContext().clearRect(0, 0, this.getCanvas().width, this.getCanvas().height);
this.setCanvas();
ctx.translate(x, y);
ctx.scale(scale, 1);
ctx.translate(-x, -y);
this.resetCanvasLines();
this.renderGraph(this.state.points, scale);
这段代码只允许我放大图的最左边。现在我试着在这张图上选取两个点,放大它们的顶部,使它们均匀地分布在屏幕上。Y轴将始终相同

我的想法是得到两点之间的中点,放大那个位置,我觉得应该可以,但我就是不能让它工作。我的图形宽度为3010px,分为5段602px。我想从x1=602和x2=1806进行缩放,其中点为1204。是否有一种技术可以正确计算秤量

rangeFinder(from, to) {
  let points = this.state.points;
  if (points.length === 0) {
    return;
  }

  let ctx = this.getCanvasContext();
  let canvasWidth = this.getCanvasWidth();
  let canvasHeight = this.getCanvasHeight() / 2;
  let seconds = this.state.seconds;
  let second = canvasWidth / seconds;
  let scale = 1;
  // My graph starts from zero, goes up to 5 and the values are to represent seconds. 
  // This gets the pixel value for the fromX value.
  let fromX = from * second;
  to = isNaN(to) ? 5 : to;

  // Get the pixel value for the to location. 
  let toX = parseInt(to) * second;
  let y = canvasHeight / 2;

  // get the midpoint between the two points.
  let midpoint = fromX + ((toX - fromX) / 2);

  // This is where I really go wrong. I'm trying to calculate the scale amount
  let zoom = canvasWidth - (toX - fromX);
  let zoomPixel = (zoom / 10) / 1000;
  let scaleAmount = scale + ((zoom / (canvasWidth / 100)) / 100) + zoomPixel;

  ctx.clearRect(0, 0, this.getCanvas().width, this.getCanvas().height);
  this.setCanvas();

  // translate and scale.
  ctx.translate(midpoint, y);
  ctx.scale(scaleAmount, 1);
  ctx.translate(-midpoint, -y);

  this.resetCanvasLines();
  this.renderGraph(points);

}

任何帮助都会很好,谢谢。

比例=5/3=总宽度/零件宽度。
缩放后,x=602应该移动到602*5/3~1000。将新图像翻译为-1000。没有必要找到中间点。

Vijay,你这个天才,工作得很好。我算错了!幸亏你没站在我面前,因为我打了五个高球,可能会把你的手腕弄断