所以我用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轴将始终相同。
我的想法是获得两点之间的中点并放大该位置,我觉得应该可以工作,但我无法让它工作。我的图形宽度为3010像素,并分为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);
}
任何帮助都会很棒,谢谢。
答案 0 :(得分:1)
比例= 5/3 =总宽度/部分宽度。 缩放后,x = 602应该已经移动到602 * 5 / 3~1000。将新图像翻译为-1000。没有必要找到中点。