2017-08-08 47 views
-2

当我尝试翻译第一张图并保留第二张图时,第二张图也会移动,因此我试图将第二张图固定在指定位置,并且仅在第一张转换函数的值发生变化时才翻译第一张图。如何在不影响其他绘图的情况下在HTML 5中转换和旋转绘图?

我的代码: -

<html> 
 
    <body> 
 
    <canvas id="myCanvas" width="300" height="150" style="border:1px solid 
 
     #d3d3d3;"> 
 
    Your browser does not support the HTML5 canvas tag. 
 
    </canvas> 
 
    <script> 
 
    var c = document.getElementById("myCanvas"); 
 
    var ctx = c.getContext("2d"); 
 
    
 
    ctx.translate(10,10); 
 
    ctx.fillRect(70,40,44,30); 
 
    ctx.fillRect(10,10,40,30); 
 
    </script> 
 
</body> 
 
</html>

回答

0

<html> 
 
    <body> 
 
    <canvas id="myCanvas" width="300" height="150" style="border:1px solid 
 
     #d3d3d3;"> 
 
    Your browser does not support the HTML5 canvas tag. 
 
    </canvas> 
 
    <script> 
 
    var c = document.getElementById("myCanvas"); 
 
    var ctx = c.getContext("2d"); 
 
    ctx.save(); 
 
    ctx.translate(10,10); 
 
    ctx.fillRect(70,40,44,30); 
 
    ctx.restore(); 
 
    ctx.fillRect(10,10,40,30); 
 
    </script> 
 
</body> 
 
</html>

您可以使用save()restore()。在翻译完成之前保存画布状态之前,请将其恢复。

0

<html> 
 
    <body> 
 
    <canvas id="myCanvas" width="300" height="150" style="border:1px solid 
 
     #d3d3d3;"> 
 
    Your browser does not support the HTML5 canvas tag. 
 
    </canvas> 
 
    <script> 
 
    var c = document.getElementById("myCanvas"); 
 
    var ctx = c.getContext("2d"); 
 
    
 
    ctx.translate(10,10); 
 
    ctx.fillRect(70,40,44,30); 
 
    ctx.rotate(20*Math.PI/180); 
 
    ctx.fillRect(10,10,40,30); 
 
    </script> 
 
</body> 
 
</html>

相关问题