我有以下網頁:
var box_x = 30;
var box_y = 30;
var box_width = 30;
var box_height = 30;
var box_direction = 20; // Degrees clockwise
function draw_box() {
var c = document.getElementById("area");
var ctx = c.getContext("2d");
ctx.clearRect(0, 0, 500, 500);
ctx.rotate(box_direction * Math.PI / 180);
ctx.fillRect(box_x, box_y, 100, 50);
box_x = 2;
}
setInterval(draw_box, 1000);
<h1>Welcome</h1>
<canvas id="area" width="500px" height="500px" style="border: 1px solid #0000aa" />
</canvas>
為什么盒子不只是向右移動?
uj5u.com熱心網友回復:
不知道您為什么使用rotate,但最簡單的方法是通過向右更新來保持矩形向右移動。另外,我使用requestAnimationFramesetInterval 對性能不友好
下面的作業代碼
var box_x = 30;
var box_y = 30;
var box_width = 30;
var box_height = 30;
var box_direction = 20; // Degrees clockwise
function draw_box() {
requestAnimationFrame(draw_box);
var c = document.getElementById("area");
var ctx = c.getContext("2d");
ctx.clearRect(0, 0, 500, 500);
ctx.fillRect(box_x, box_y, 100, 50);
box_x = 2;
}
requestAnimationFrame(draw_box);
<h1>Welcome</h1>
<canvas id="area" width="500px" height="500px" style="border: 1px solid #0000aa"/>
</canvas>
uj5u.com熱心網友回復:
ctx.rotate 從左上角旋轉整個畫布,因此您應該首先使用 ctx.translate 將左上角移動到樞軸(即框的左上角),然后執行相同但相反的操作,以便您重置畫布的旋轉和平移
var box_x = 30;
var box_y = 30;
var box_width = 30;
var box_height = 30;
var box_direction = 20; // Degrees clockwise
function draw_box() {
var c = document.getElementById("area");
var ctx = c.getContext("2d");
ctx.clearRect(0, 0, 500, 500);
ctx.translate(box_x, box_y);
ctx.rotate(box_direction * Math.PI / 180);
ctx.fillRect(0, 0, 100, 50);
ctx.rotate(-box_direction * Math.PI / 180);
ctx.translate(-box_x, -box_y);
box_x = 2;
}
setInterval(draw_box, 1000);
<h1>Welcome</h1>
<canvas id="area" width="500px" height="500px" style="border: 1px solid #0000aa" />
</canvas>
uj5u.com熱心網友回復:
因為你有ctx.rotate(box_direction * Math.PI / 180);。這是隨著盒子旋轉的。
<html>
<head>
<title>Rectangles wandering around aminlessly</title>
</head>
<body
<h1>Welcome</h1>
<canvas id="area" width="500px" height="500px" style="border: 1px solid #0000aa"/>
</canvas>
<script lang="javascript">
var box_x = 30;
var box_y = 30;
var box_width = 30;
var box_height = 30;
var box_direction = 20; // Degrees clockwise
function draw_box() {
var c = document.getElementById("area");
var ctx = c.getContext("2d");
ctx.clearRect(0, 0, 500, 500);
ctx.fillRect(box_x, box_y, 100, 50);
box_x = 2;
}
setInterval(draw_box, 1000);
</script>
</body>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/434102.html
標籤:javascript html
