【问题标题】:How can I change css properties of an object located in canvas with js?如何使用 js 更改位于画布中的对象的 css 属性?
【发布时间】:2018-11-05 13:54:29
【问题描述】:

我正在制作一款游戏,但我遇到了一个问题。当我的角色向左移动时,我需要反转我的角色,我不能只创建一个反转图像并使用它,我也不能反转画布,因为我会有一些新角色,它们不应该反转。一种方法是引用我的角色 css 属性并使用 js 添加如下内容:

-webkit-transform: scaleX(-1);
transform: scaleX(-1);

我可以在画布中做到这一点吗?怎么做?


用箭头移动

var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var lifes = 700;

var fon = new Image();
fon.src = "https://i.stack.imgur.com/HjXpq.jpg";

var life_red = new Image();
life_red.src = "https://i.stack.imgur.com/sGZ7l.jpg";

var life_green = new Image();
life_green.src = "https://i.stack.imgur.com/9eWXX.jpg";

var iron_man_img = new Image(); // Player walking right
iron_man_img.src = 'https://i.stack.imgur.com/aeTtS.png';
var iron_man = {
  x: 300,
  y: 50,
  dx: 100,
  dy: 0.1,
  dfly: 500,
  run: 0, //animation
  runspeed: 5, // animation speed
  fly: false,
  timeforflying: 0,
  alive: true
}
var keys = {};

function setKey(event, status) {
  var code = event.keyCode;
  var key;
  if (code == 32) {
    key = "Space";
  } else if (code == 37) {
    key = "Left";
  } else if (code == 38) {
    key = "Up";
  } else if (code == 39) {
    key = "Right";
  } else if (code == 40) {
    key = "Down";
  } else {
    key = String.fromCharCode(code);
  }
  keys[key] = status;
}

document.addEventListener('keydown', function(e) {
  setKey(e, true);
});
document.addEventListener('keyup', function(e) {
  setKey(e, false);
});
document.addEventListener('blur', function() {
  keys = {};
});

function isDown(key) {
  return keys[key];
}
iron_man_img.onload = function() {
  last = Date.now();
  game();
}

function game() {

  var now = Date.now();
  var dt = (now - last) / 1000;
  update(dt);
  render();
  last = now;
  requestAnimFrame(game);
}

function update(dt) {
  if (isDown("Right") || isDown("D")) {
    iron_man.run += iron_man.runspeed * dt;
    iron_man.x += iron_man.runspeed * dt * 10;
  }
  if (isDown("Left") || isDown("A")) {
    iron_man.run += iron_man.runspeed * dt;
    iron_man.x -= iron_man.runspeed * dt * 10;
  }
  //console.log(iron_man.runspeed * dt);
}

function render() {
  var width = window.innerWidth;
  var height = window.innerHeight;
  //console.log(width/height);
  //console.log(700/500);
  if (width / height > 700 / 500) {
    $('canvas').css('height', height);
    $('canvas').css('width', height / 500 * 700);
  } else {
    $('canvas').css('width', width);
    $('canvas').css('height', width / 700 * 500);
  }


  context.fillStyle = "green";
  curr_life = new Image();
  curr_life.src = "Sprites/life_green.jpg";
  for (var i = 0; i < 1800; i++) { // HP
    if (i == lifes) {
      curr_life.src = "Sprites/life_red.jpg";
    }
    //context.drawImage(curr_life, 240, 268, i, 0, 1, 1);
    context.drawImage(curr_life, i, 0, 10, 10);
  }
  if (lifes != 0) {
    //lifes--;
  }
  context.drawImage(fon, 0, 0, 1000, 1000);
  context.drawImage(iron_man_img, 44 * (Math.round(iron_man.run) % 8) + 1.2, 0, 44, 65, iron_man.x, iron_man.y, 50, 60);
  //console.log(iron_man.run);
  //iron_man.x+=1; 
  //iron_man.x+=1; 
}
var requestAnimFrame = (function() {
  return window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    window.oRequestAnimationFrame ||
    window.msRequestAnimationFrame ||
    function(callback) {
      window.setTimeout(callback, 50);
    };
})();
#canvas {
  background-color: lightblue;
  margin: 0 auto;
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  display: block;
  padding: 0;
}

body {
  overflow: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div align="center" class="canvas-div">
  <canvas id="canvas" width="700" height="500" style="border: 1px solid black" class="canvas">
    Canvas is not working in your browser
  </canvas>
</div>

【问题讨论】:

  • 您可能希望将代码缩减为 minimal reproducible example
  • @Haem 对不起,这是我能写的最少的代码。所有零件都是必需的。
  • 为什么不能使用反转图像?这样更快。 stackoverflow.com/questions/8168217/…
  • @arieljuod 问题是我试过用它,canvas真的很滞后。真的落后了。
  • 我不明白为什么会滞后,左右精灵应该都在同一个图像文件上,而不是不同的图像文件,所以向左或向右走应该有相同的影响,因为它只会显示来自同一图像的一帧。

标签: javascript css html5-canvas


【解决方案1】:

是的,最好的办法是画布比例,为了使其正常工作,必须进行一些更改,但我会尽力解释它们。

为了注意方向,我添加了 iron_man.z 并使用 -1 表示朝左,使用 1 表示朝右,这是因为这就是缩放的工作原理。

接下来,在update() 中,我们需要根据我们按下的键将iron_man.z 设置为1 或-1。

现在是复杂的位。我们运行 context.save() 来记住我们的所有设置,然后再使用翻译和缩放。

我们必须平移来设置我们希望原点成为钢铁侠中心的比例原点。要计算出我们使用 iron_man.x + width/2 和 iron_man.y + height/2 (context.translate(iron_man.x + 25, iron_man.y + 30)),这意味着 Ironman 的位置也需要不同,但我们需要先进行缩放。

对于规模,我们只需要iron_man.z,所以我们有这个context.scale(iron_man.z,1)

最后我们绘制图像,现在因为我们已经将原点设置为 Ironman 的中心,所以我们需要将 x 和 y 坐标放在 -(width/2), -(height/2)。

最后,我们想用context.restore()恢复画布

var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var lifes = 700;

var fon = new Image();
fon.src = "https://i.stack.imgur.com/HjXpq.jpg";

var life_red = new Image();
life_red.src = "https://i.stack.imgur.com/sGZ7l.jpg";

var life_green = new Image();
life_green.src = "https://i.stack.imgur.com/9eWXX.jpg";

var iron_man_img = new Image(); // Player walking right
iron_man_img.src = 'https://i.stack.imgur.com/aeTtS.png';
var iron_man = {
  x: 300,
  y: 50,
  z: -1,
  dx: 100,
  dy: 0.1,
  dfly: 500,
  run: 0, //animation
  runspeed: 5, // animation speed
  fly: false,
  timeforflying: 0,
  alive: true
}
var keys = {};

function setKey(event, status) {
  var code = event.keyCode;
  var key;
  if (code == 32) {
    key = "Space";
    console.log(iron_man)
  } else if (code == 37) {
    key = "Left";
  } else if (code == 38) {
    key = "Up";
  } else if (code == 39) {
    key = "Right";
  } else if (code == 40) {
    key = "Down";
  } else {
    key = String.fromCharCode(code);
  }
  keys[key] = status;
}

document.addEventListener('keydown', function(e) {
  setKey(e, true);
});
document.addEventListener('keyup', function(e) {
  setKey(e, false);
});
document.addEventListener('blur', function() {
  keys = {};
});

function isDown(key) {
  return keys[key];
}
iron_man_img.onload = function() {
  last = Date.now();
  game();
}

function game() {

  var now = Date.now();
  var dt = (now - last) / 1000;
  update(dt);
  render();
  last = now;
  requestAnimFrame(game);
}

function update(dt) {
  if (isDown("Right") || isDown("D")) {
    iron_man.run += iron_man.runspeed * dt;
    iron_man.x += iron_man.runspeed * dt * 10;
    iron_man.z = 1;
  }
  if (isDown("Left") || isDown("A")) {
    iron_man.run += iron_man.runspeed * dt;
    iron_man.x -= iron_man.runspeed * dt * 10;
    iron_man.z = -1;
  }
  //console.log(iron_man.runspeed * dt);
}

function render() {
  var width = window.innerWidth;
  var height = window.innerHeight;
  //console.log(width/height);
  //console.log(700/500);
  if (width / height > 700 / 500) {
    $('canvas').css('height', height);
    $('canvas').css('width', height / 500 * 700);
  } else {
    $('canvas').css('width', width);
    $('canvas').css('height', width / 700 * 500);
  }


  context.fillStyle = "green";
  curr_life = new Image();
  curr_life.src = "Sprites/life_green.jpg";
  for (var i = 0; i < 1800; i++) { // HP
    if (i == lifes) {
      curr_life.src = "Sprites/life_red.jpg";
    }
    //context.drawImage(curr_life, 240, 268, i, 0, 1, 1);
    context.drawImage(curr_life, i, 0, 10, 10);
  }
  if (lifes != 0) {
    //lifes--;
  }
  context.drawImage(fon, 0, 0, 1000, 1000);
  context.save();
  context.translate(iron_man.x + 25, iron_man.y + 30);
  context.scale(iron_man.z, 1);
  context.drawImage(iron_man_img, 44 * (Math.round(iron_man.run) % 8) + 1.2, 0, 44, 65, -25, -30, 50, 60);
  context.restore();
  //console.log(iron_man.run);
  //iron_man.x+=1; 
  //iron_man.x+=1; 
}
var requestAnimFrame = (function() {
  return window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    window.oRequestAnimationFrame ||
    window.msRequestAnimationFrame ||
    function(callback) {
      window.setTimeout(callback, 50);
    };
})();
#canvas {
  background-color: lightblue;
  margin: 0 auto;
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  display: block;
  padding: 0;
}

body {
  overflow: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div align="center" class="canvas-div">
  <canvas id="canvas" width="700" height="500" style="border: 1px solid black" class="canvas">
    Canvas is not working in your browser
  </canvas>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-23
    • 2019-12-24
    • 1970-01-01
    • 1970-01-01
    • 2019-03-09
    • 2016-01-09
    • 1970-01-01
    • 2013-08-07
    相关资源
    最近更新 更多