很抱歉造成误解,我对实际在 Stack Exchange 上发帖还是很陌生。我的问题不是完全理解 save() 和 restore() 是如何工作的(当然),但这是我最好的解释;执行您希望稍后应用的转换/状态更改并保存()那些,然后将自己与先前的状态更改分开并执行一组不同的状态更改以应用于您的下一个图像/形状,继续执行此操作直到您达到您想要独立转换的最后一个项目(作为注释,对于最后一个项目,您不必保存,只需绘制您想要的项目)。现在所有的转换都完成并保存了,你已经绘制了你的第一个项目,你使用 restore() 然后绘制你想要绘制的下一个项目,对你想要绘制的所有项目继续这个。需要注意的一件重要事情是 globalCompositeOperation 属性,请搜索它,因为它决定了图像的堆叠方式。希望这个解释是合理的,我很抱歉没有早点这样做。
function update() {
//Merely clearing the canvas in the area our image was previously in.
program.ctxT.clearRect(x - 35, 0 - 18, 108, 81);
//Rotate canvas and save this state, this will be applied to the body or underlying element.
rotCentre(35, 25, Math.PI / -135);
program.ctxT.save();
//This keeps track of the body rotation.
rot++;
//Applies the same rotation as earlier to move the head with the body.
program(35, 25, Math.PI / -135);
/* Although the head moves with the body, it should not changes its facing, so compensation.
The title says two images moving in opposite directions, but this only kind of does that,
if you do want them to be visually moving in opposite directions, just multiply the rot by
a number greater than one.*/
program(8, 8, rot * Math.PI / 135);
//Draw the overlaying image (head).
program.ctxT.drawImage(program.imgHead, x, 0);
//Moving onto the lower layer, restore the transformations we are using for it and draw.
program.ctxT.restore();
program.ctxT.drawImage(program.imgBody, x - 35, -17.3);
}
function rotCentre(centreX, centreY, angle) {
//This allows the head to be overlayed.
program.ctxT.globalCompositeOperation = 'destination-over';
//First translate the context so that it will rotate around the image's centre.
program.ctxT.translate(x + centreX, 0 + centreY);
program.ctxT.rotate(angle);
//Remember to put the context back to its original position!
program.ctxT.translate(-(x + centreX), -(0 + centreY));
}