画布重复矩形

时间:2014-12-06 22:10:26

标签: javascript css html5 css3 canvas

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

代码:

<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动画,这是否可行?

1 个答案:

答案 0 :(得分: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);
};
<canvas id=canvas width=320 height=320></canvas>

您应该能够采用所示的原则来满足您的需求。希望这有帮助!