(HTML5 画布)填充样式 img 不会随我的地形路径移动

(HTML5 Canvas) Fillstyle img doesnt move with my terrain path

本文关键字:我的 移动 路径 画布 HTML5 填充 img 样式      更新时间:2023-09-26

我正在写一个画布游戏。我有一些随机生成的地形,用lineTo(),closePath()制作,并用img填充为fillStyle。目前为止,一切都好。但是当我使用 js 移动地形时,img 不会随之移动并停留在同一个地方。有什么想法吗?咔嚓。

在进行填充之前,您需要随动作平移画布。还要记得在制作形状之前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>

相关文章: