(HTML5 Canvas)Fillstyle img不会随着我的地形路径移动

时间:2016-02-09 11:41:42

标签: javascript canvas html5-canvas

我正在写一个画布游戏。我有一些使用lineTo(),closePath()制作的随机生成的地形,并用img填充为fillStyle。到现在为止还挺好。但是当我用js移动地形时,img不会随之移动并停留在同一个地方。有任何想法吗? TNX。

1 个答案:

答案 0 :(得分:0)

在进行填充之前,您需要使用移动平移画布。在制作你的形状之前,请记住beginPath

var pattern = document.getElementById('pattern');
var can = document.getElementById('can');
var ctx = can.getContext('2d');

var w = can.width = 300;
var h = can.height = 200;


pattern.width = pattern.height = 20;
var pctx = pattern.getContext('2d');
pctx.fillStyle = 'white';
pctx.fillRect(0, 0, 20, 20);
pctx.fillStyle = 'red';
pctx.fillRect(0, 0, 10, 10);
pctx.fillRect(10, 10, 10, 10);
pctx.fillRect(2, 12, 6, 6);
pctx.fillRect(12, 2, 6, 6);

var p = ctx.createPattern(pattern, 'repeat');

var x = 50;
var y = 50;
var radius = 50;
var xStep = 1;
var yStep = 2;
var trans = "on";

function ani() {
  ctx.fillStyle = "black";
  ctx.fillRect(0, 0, w, h);
  ctx.moveTo(x, y);
  // beginPath clears any existing path
  ctx.beginPath();
  ctx.arc(x, y, radius, 0, Math.PI * 20);
  ctx.fillStyle = p;
  if (trans == "on") {
    ctx.save();
    // translate will offset the fill pattern
    ctx.translate(x, y);
    ctx.fill();
    ctx.restore();
  } else {
    ctx.fill();
  }
  x += xStep;
  y += yStep;
  if (x > (w - radius) || x < radius) xStep *= -1;
  if (y > (h - radius) || y < radius) yStep *= -1;
  requestAnimationFrame(ani);
}

ani();

var btnOff = document.getElementById('trans_off');
var btnOn = document.getElementById('trans_on');

btnOff.addEventListener('click',function(){
  btnOff.className = "selected";
  btnOn.className = "";
  trans = "off";
});

btnOn.addEventListener('click',function(){
  btnOff.className = "";
  btnOn.className = "selected";
  trans = "on";
});
body {
  background-color: #555555;
  color: #F0F0F0;
  font-family: sans-serif;
}
button {
  color: #cccccc;
  background-color: #333333;
  border: 1px solid #cccccc;
}
button.selected {
  color: white;
  font-weight: bold;
}
Translate
<button id="trans_off">off</button>
<button id="trans_on" class="selected">on</button>
<hr/>
<canvas id="pattern"></canvas>
<canvas id="can"></canvas>