JavaScript上下文翻译在电子版中不起作用



我在画布游戏中使用ctx.translate(x, y)移动相机。但出于某种原因,这是行不通的。

这就是我正在使用的:

setCameraPos: function(x, y) {
//ctx.save()
ctx.translate(x, y)
ctx.setTransform(1, 0, 0, 1, 0, 0)
//ctx.restore()
}

它根本不起作用。它不会改变相机的位置。有错误吗?没有任何错误。我正在使用Electron 3.0.3 Beta

我接受任何库

const canvas = document.getElementById('main')
const ctx = canvas.getContext('2d')
ctx.fillStyle = 'red'
ctx.fillRect(0, 0, 30, 30)
// This doesn't work | VVV
ctx.translate(20, 20)
ctx.setTransform(1, 0, 0, 1, 0, 0)
#main {
background-color: black;
}
<canvas id="main">
</canvas>

根据您提供的信息,翻译操作在任何地方都不起作用,不仅仅是在Electron中。

ctx.setTransform()方法将变换矩阵设置为绝对值,当前矩阵将被丢弃,并且传递的值是您的矩阵将被设置的值
1, 0, 0, 1, 0, 0是本机矩阵变换(即未变换(的值。

因此,调用ctx.setTransform(1, 0, 0, 1, 0, 0)将把transform矩阵重置为默认值,并使所有对相对translate((rotate((transform((的调用都无效。

这些方法是相对的,因为它们加起来就是当前的矩阵值。例如,

ctx.translate(10, 10);
// here next drawing will be offset by 10px in both x and y direction
ctx.translate(40, -10);
// this adds up to the current 10, 10, so we are now offset by 30, 0

如果你想让翻译工作,不要在这里调用setTransform,甚至不要用setTransform(1, 0, 0, 1, 20, 20)代替它

此外,在您的代码片段中,您将在绘制之后设置转换矩阵。转换将仅应用于下一个图形,而不会应用于上一个图形。

现在,您可能处于动画循环中,需要在每个循环中重置矩阵。在这种情况下,在绘图循环开始时调用ctx.setTransform(1,0,0,1,0,0),或者作为最后一个操作,并在绘图前调用translate((

const canvas = document.getElementById('main');
const ctx = canvas.getContext('2d');
let x = 0;
ctx.fillStyle = 'red'
anim();
function draw() {
// reset the matrix so we can clear everything
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, canvas.width, canvas.height);
//set the transform before drawing
ctx.translate(x - 30, 20)
//which is actually the same as 
//ctx.setTransform(1, 0, 0, 1, x, 20);
ctx.fillRect(0, 0, 30, 30);
}
function anim() {
x = (x + 2) % (canvas.width + 60);
draw();
requestAnimationFrame(anim);
}
#main {
background-color: black;
}
<canvas id="main"></canvas>

最新更新