【问题标题】:How to translate and rotate drawing in html 5 without effecting another drawing?如何在不影响其他绘图的情况下翻译和旋转html5中的绘图?
【发布时间】:2017-08-08 07:53:20
【问题描述】:
当我尝试平移第一张图并保持第二张图固定时,第二张图也会移动,因此我试图将第二张图固定在指定位置,并且仅在我更改第一个平移函数的值时才平移第一张图。
我的代码:-
<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>
【问题讨论】:
标签:
javascript
html
html5-canvas
【解决方案1】:
<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() 。翻译前保存画布状态,完成后恢复。
【解决方案2】:
<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>