首页 > 解决方案 > 使用 Javascript Canvas 将图像添加到对象

问题描述

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

我想使用的图像 -

下面是示例所在的代码笔。

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();
body,
#canvas 
{
  margin: 0;
  padding: 0;
}

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

标签: javascriptanimationcanvas

解决方案


推荐阅读