誤解について申し訳ありませんが、私はまだ実際にStackExchangeに投稿するのは初めてです。私の問題は、save()とrestore()がどのように機能するかを完全に理解することではありませんでしたが(もちろん)、これが私の最善の説明です。後で適用する変換/状態変更を実行し、それらをsave()してから、前の状態変更から自分自身を分離し、次の画像/形状に適用するために別の状態変更のセットを実行します。独立して変換したい最後のアイテム(注として、最後のアイテムでは、保存する必要はありません。必要なアイテムを描画するだけです)。すべての変換が完了して保存され、最初のアイテムを描画したので、restore()を使用して、描画したい次のアイテムを描画します。これを、描画したいすべてのアイテムに対して続行します。注意すべき重要なことの1つは、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));
}