【问题标题】:Canvas repeat rect画布重复矩形
【发布时间】:2014-12-07 08:35:51
【问题描述】:

我正在尝试为我的背景制作某种图案,但我想自己绘制矩形,而不是使用图像。

代码:

<canvas id="myCanvas" width="33" height="33"></canvas>
<script>
  var canvas = document.getElementById('myCanvas');
  var context = canvas.getContext('2d');

  context.beginPath();
  context.rect(0, 0, 32, 32);
  context.fillStyle = 'black';
  context.fill();
  context.lineWidth = 1;
  context.strokeStyle = 'silver';
  context.stroke();
</script>

到目前为止,它创建了我想要的矩形。现在我想在 X 和 Y 中重复它。

此外,如果我想稍后为每个方块(相同的动画)添加 mouseOnHover 动画,这是一种可行的方法吗?

【问题讨论】:

    标签: javascript html css canvas


    【解决方案1】:

    这是创建鼠标悬停矩形网格的方法:

    var ctx = canvas.getContext("2d"),
        cw = 32,
        ch = 32,
        w = canvas.width,
        h = canvas.height;
    
    ctx.translate(0.5, 0.5);
    ctx.beginPath(); // not neede here, but if in a larger project
    
    for(var y = 0; y < h; y += ch) {
     for(var x = 0; x < w; x += cw) {
          ctx.rect(x, y, cw-2, ch-2); // give 1px space  
      } 
    }
    
    ctx.fillStyle = "gray";
    ctx.strokeStyle = "#000";
    
    ctx.lineWidth=1;
    ctx.fill();
    ctx.stroke();
    
    canvas.onmousemove = function(e) {
    
      var rect = this.getBoundingClientRect(),
          x = e.clientX - rect.left,
          y = e.clientY - rect.top,
          cx = ((x / cw)|0) * cw,  //quantize mouse pos to grid
          cy = ((y / ch)|0) * ch;
      
      ctx.fillStyle = "red";
      ctx.fillRect(cx+1, cy+1, cw-3, ch-3);
    };
    &lt;canvas id=canvas width=320 height=320&gt;&lt;/canvas&gt;

    您应该能够根据您的需要采用所显示的原则。希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 2020-01-25
      • 2016-02-24
      • 1970-01-01
      • 2016-12-03
      • 2011-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多