使用Javascript Canvas将图像添加到对象

时间:2018-05-23 17:04:38

标签: javascript animation canvas

尝试用png图像替换黑色方块。 不确定正确的技术。

我想要使用的图像 -

以下是该示例所在的codepen。

https://codepen.io/roys/pen/pJGJON



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

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

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

function drawRectangle(rect) {
  context.beginPath();
  context.rect(rect.x, rect.y, rect.width, rect.height);
  context.fillStyle = rect.color;
  context.fill();    
}

//moving rectangle
var mover = {
  x: 0,
  y: 0,
  width: 40,
  height: 40,
  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 += 10;
  else 
    mover.x -= 10;
  
  if (mover.down)
    mover.y += 10;
  else 
    mover.y -= 10;
  
  drawRectangle(mover);
}

animate();
&#13;
body,
#canvas 
{
  margin: 0;
  padding: 0;
}

#canvas {
  display: block;
  background-color: lightblue;
}
&#13;
<canvas id="canvas"></canvas>
&#13;
&#13;
&#13;

0 个答案:

没有答案