Bis*_*der 3 javascript html5 canvas rotation
所以我的问题就在于此.我在画布上使用javascript绘制多边形.我也尝试使用sin/cos基于任何给定点旋转那些多边形.我避免翻译和画布旋转.旋转发生在鼠标移动上.
事情的结果很奇怪.我的多元素由于某种原因倾向于缩小,我无法弄清楚原因.
我的猜测是围绕数学运算sin/cos结合如何在矩阵周围设置坐标?也许我应该围绕价值观或?我不确定也太困惑了.
以下代码正常运行.如果您可以运行代码,您可以得到我的意思任何帮助或解释为什么会发生这种情况将受到高度赞赏.干杯.
<script type="text/javascript">
var set =
{
canvas:'canvas',
fps:1000/60
}
var gObjects = [];
function deg2rads(deg) { return deg*Math.PI/180; }
function drawPoly(object)
{
if (object.vertexPoints)
{
var ctx = document.getElementById(set.canvas).getContext('2d');
ctx.beginPath();
ctx.moveTo(object.vertexPoints[0][0],object.vertexPoints[0][1]);
ctx.fillStyle = '#f00';
for (i=1;i<object.vertexPoints.length;i++)
{
ctx.lineTo(object.vertexPoints[i][0],object.vertexPoints[i][1]);
}
ctx.closePath();
ctx.fill();
}
}
function block(vertex)
{
if (vertex) { this.vertexPoints = vertex; }
}
function rotate(object,degrees) {
vPoint = object.vertexPoints;
for (i=0;i<vPoint.length;i++)
{
rads = deg2rads(degrees);
pX= 300;
pY= 540;
object.vertexPoints[i][0] = Math.cos(rads) * (vPoint[i][0] - pX) - Math.sin(rads) * (vPoint[i][1]-pY) + pX;
object.vertexPoints[i][1] = Math.sin(rads) * (vPoint[i][0] - pX) + Math.cos(rads) * (vPoint[i][1]-pY) + pY;
}
}
function mainGameLoop ()
{
var ctx = document.getElementById(set.canvas).getContext('2d');
ctx.clearRect(0,0,600,600);
drawPoly(gObjects[0]);
var gameTimer = setTimeout(mainGameLoop,set.fps);
}
function iNitCanvas() {
var test = [[100,500],[500,500],[500,580],[100,580]];
var obj = new block(test);
gObjects[0] = new block(test);
mainGameLoop();
}
function mouseCoords() {
rotate(gObjects[0],-10);
}
</script>
<body onmousemove="mouseCoords();" onLoad="iNitCanvas();">
<input type="button" id="showCube" onclick="iNit();" value="GO!"/>
<canvas id="canvas" width="600" height="600" style="border:1px solid black;"></canvas>
</div>
</body>
Run Code Online (Sandbox Code Playgroud)
你的数学很好.罪魁祸首隐藏在这两行中:
object.vertexPoints[i][0] = Math.cos(rads) * (vPoint[i][0] - pX) - Math.sin(rads) * (vPoint[i][1]-pY) + pX;
object.vertexPoints[i][1] = Math.sin(rads) * (vPoint[i][0] - pX) + Math.cos(rads) * (vPoint[i][1]-pY) + pY;
Run Code Online (Sandbox Code Playgroud)
第二行使用vPoint[i][0],已经被第一行修改(vPoint并object.vertexPoints指向同一个数组.)
用以下内容替换这两行可以防止收缩:
var point = [ vPoint[i][0], vPoint[i][1] ];
object.vertexPoints[i][0] = Math.cos(rads) * (point[0] - pX) - Math.sin(rads) * (point[1]-pY) + pX;
object.vertexPoints[i][1] = Math.sin(rads) * (point[0] - pX) + Math.cos(rads) * (point[1]-pY) + pY;
Run Code Online (Sandbox Code Playgroud)