2013-03-26 45 views
0

我一直无法使用canvas状态()和restore()函数在相反方向上旋转两个图像。任何解决方案都非常感谢,谢谢!如何在相同方向上旋转[相同画布上]的两幅图像?

这里是我的代码:

program.ctxT.globalCompositeOperation = 'destination-over'; 
program.ctxT.save(); 

program.ctxT.clearRect(x - 1, 0 - 1, 72, 62); 
program.ctxT.translate(x + 35, 0 + 25); 
program.ctxT.rotate(Math.PI/135); 
program.ctxT.translate(-(x + 35), -(0 + 25)); 
program.ctxT.drawImage(program.imgBody, x, 0); 
program.ctxT.restore(); 

program.ctxT.globalCompositeOperation = 'destination-over'; 
program.ctxT.save(); 

program.ctxT.translate(x + 35, 0 + 25); 
program.ctxT.rotate(Math.PI/-135); 
program.ctxT.translate(-(x + 35), -(0 + 25)); 
program.ctxT.drawImage(program.imgHead, x, 0); 
program.ctxT.restore(); 
+0

要么删除您的问题,要么回答问题并将其选为接受的答案。所以在标题中SO不做“解决”。 – j08691

+0

完成,会不会足够? – Rjdlee

回答

0

很抱歉的误解,我还是新来实际张贴在堆栈交换。我的问题并不完全理解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)); 
} 
相关问题