alcoven
alcoven

Reputation: 321

Updating canvas animation width on window resize

Can't figure out how to get this in place. I have the right function firing but am lost when it comes to why the logic isn't working my script. I have a console.log to show the variables are updating but the animation width doesn't update with it.

Javascript

$( document ).ready(function() {


var imgTag = new Image();
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var x = canvas.width;
var y = 0;

imgTag.onload = animate;
imgTag.src = "http://foodhall.hellogriptest.com/hh/assets/medallion-bounce.png";



var h = window.innerHeight;
var w = window.innerWidth;

canvas.height = h;
canvas.width = w;


//moving image
var mover = {
  x: 0,
  y: 0,
  width: 100,
  height: 100,
  color: '#000',
  down: true,
  right: true
}

function animate() {
  clear();
  render();
  rID = requestAnimationFrame(animate);
}

function clear() {
  context.clearRect(0, 0, canvas.width, canvas.height);
}

function render() {
  //set direction
  if (mover.down && mover.y >= h - mover.height)
    mover.down = false;

  if (!mover.down && mover.y <= 0)
    mover.down = true;

  if (mover.right && mover.x >= w - mover.width)
    mover.right = false;

  if (!mover.right && mover.x <= 0)
    mover.right = true;

  //make move
  if (mover.right)
    mover.x += 6;
  else
    mover.x -= 6;

  if (mover.down)
    mover.y += 6;
  else
    mover.y -= 6;

  //drawRectangle(mover);
  drawImage(mover);

}

function drawImage(mover) {
  context.drawImage(imgTag, mover.x, mover.y); // draw image at current position
}

window.onresize = function() {  
   W = window.innerWidth;
   H = window.innerHeight;
   canvas.width = W;
   canvas.height = H;
   x = W;
  console.log(x);
  clear();
  render();
  drawImage(mover);
}


});//ready

Codepen — https://codepen.io/alcoven/pen/KROPrK

Upvotes: 0

Views: 91

Answers (1)

Devin Fields
Devin Fields

Reputation: 2544

This is a simple fix. In the beginning of your script, you are setting lowercase w and lowercase h to the width and height of the window, but in you resize function, you set W = window.innerWidth. The capital W variable is then created and assigned the innerWidth. The lowercase w variable still exists as the original width, and that is what your render is using.

Upvotes: 1

Related Questions