2017-08-08 46 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>

相關問題