0

I´m writting a canvas game. I have some random produced terrain made with lineTo(), closePath() and filled out with an img as fillStyle. So far so good. But when i move the terrain with js the img doesnt move with it and stays on the same place. Any Ideas? Tnx.

0

1 Answer 1

0

You need to translate the canvas with the movement before doing the fill. Also remember to beginPath before making your shape.

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>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.