Html5画布显示了一个grapich中的数组,但该画布没有转向

Html5 canvas showing an array in a grapich does not turn

本文关键字:数组 布没 一个 显示 布显示 grapich Html5      更新时间:2023-09-26

在这里你可以找到我的小程序的代码。

http://jsfiddle.net/joz8h9hc/

它的目的是找出如何转动描绘二维数组值的正方形,以便实现二维数学数组的可视化。

为什么它不顺时针或逆时针转动?

var canvas=document.getElementById('canvas');
    var ctx=canvas.getContext('2d');
    //GIRADOR
    ctx.translate(canvas.width / 2, canvas.height / 2);     
    //FIN GIRADOR
    var array = new Array2D(200,200);
    //MAIN
    for(i=0; i<200; i++)
    {
      for(j=0;j<200; j++)
      {
      array[i][j]=i+j;
          var r,g,b;
      r = array[i][j];
      g=50;
      b=50;
      //La parte de dibujo
      ctx.fillStyle = "rgba("+r+","+g+","+b+",100)";
      ctx.fillRect( i, j, 1, 1 );
          }
    }
    //FUNCTIONS
    function Array2D(NumOfRows,NumOfCols)
    {
    var k=new Array(NumOfRows);
    for (i = 0; i < k.length; ++i)
    k[i] = new Array(NumOfCols);
    return k; 
    }
    function Rotar(){
    //Rotamos el lienzo?
    ctx.rotate(Math.PI / 180);
     ctx.fillStyle = "red";
      ctx.fillRect( -200, -200, 600, 600 );
    for(i=0; i<200; i++)
    {
      for(j=0;j<200; j++)
      {
      array[i][j]=i+j;
      var r,g,b;
      r = array[i][j];
      g=50;
      b=50;
      //La parte de dibujo
      ctx.fillStyle = "rgba("+r+","+g+","+b+",100)";
      ctx.fillRect( i, j, 1, 1 );
      }
    }

}

context.translate将设置您的旋转点。所有后续图形都将围绕此点旋转。

因此,如果您随后绘制矩形,则绘制矩形时左上角位于您的平移点。矩形将围绕其左上角旋转。

要绕其中心点旋转矩形,您可以将fillRect的x,y设置为-wid/2,-height/2。

此外,转换(平移、旋转)是累积的,因此您可能希望将转换封装在context.savecontext.restore中,这样后续的转换就不会与以前的转换交互。

以下是示例代码和演示,演示了围绕其中心点旋转矩形:

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
// variables to define the rectangle
var x=100;
var y=100;
var width=100;
var height=75;
var radianAngle=0;
// draw the rectangle
rotateSquare();
function rotateSquare(){
  // clear the canvas
  ctx.clearRect(0,0,canvas.width,canvas.height);
  // save the unrotated context state
  ctx.save();
  // set the rotation point at the rectangle's centerpoint
  ctx.translate(x+width/2,y+height/2);
  // set the rotation angle
  ctx.rotate(radianAngle);
  // draw the rectangle
  ctx.fillRect(-width/2,-height/2,width,height);
  ctx.strokeRect(-width/2,-height/2,width,height);
  // restore the context to its unrotated state
  ctx.restore();
}
$("#test").click(function(){
  // reset the angle
  radianAngle+=Math.PI/60;
  // call rotateSquare
  rotateSquare();
});
canvas{border:1px solid red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button id="test">Rotate</button><br>
<canvas id="canvas" width=300 height=300></canvas>