我正在使用ctx.translate(x, y)
在 Canvas 游戏中移动相机。但由于某种原因,这不起作用。
这就是我正在使用的:
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)
会将您的变换矩阵重置为其默认值,并使所有对相对 translate()、rotate() 或 transform() 的调用无用。 p>
这些方法是相对的,因为它们加起来等于当前的矩阵值。例如,
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>
关于JavaScript 上下文翻译在 Electron 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53375715/