当您 用于放大画布,然后用于移动画布时,方向可能看起来是相反的。这是因为该方法根据其当前坐标系移动画布,该坐标系已由该方法缩放。
为了更好地理解这一点,请考虑以下示例:
// Translate the canvas by 50 pixels to the right and 50 pixels down
ctx.translate(50, 50);
// Set the scaling factor to 2
ctx.scale(2, 2);
// Draw a rectangle
ctx.fillRect(0, 0, 50, 50);
在此示例中,该方法将画布的大小加倍,因此矩形的大小将是不缩放时的两倍。但是,该方法基于其原始坐标系(而不是缩放的坐标系)移动画布。因此,当我们向右平移 50 像素和向下平移 50 像素时,它似乎在每个方向上移动了 100 像素,因为坐标系已缩放了 2 倍。
若要解决此问题,可以颠倒 和 方法的顺序。例如:scale()translate()
// Set the scaling factor to 2
ctx.scale(2, 2);
// Translate the canvas by 50 pixels to the right and 50 pixels down
ctx.translate(50, 50);
// Draw a rectangle
ctx.fillRect(0, 0, 50, 50);
当使用ctx.translate()后跟随ctx.scale()时,画布移动的方向可能会因坐标系缩放而产生反向效果。为解决此问题,应先执行缩放操作,再进行移动。例如,先调用ctx.scale(2,2)缩放,然后使用ctx.translate(50,50)移动,这样可以按照预期移动画布。
3745

被折叠的 条评论
为什么被折叠?



