如何删除精灵区域中不需要的部分

时间:2015-09-06 12:09:59

标签: javascript canvas sprite

我们如何使用这个硬币精灵图像(假设背景不透明,但是白色)动画http://blocksjs.com/demos/block/images/coin.png而没有获得白色部分?假设我们只想要硬币,而不是白色背景,因为,让我们说,画布上的背景是黑色的。我们怎样才能做到这一点?

1 个答案:

答案 0 :(得分:2)

提供的图像是透明的,因此无需消除白色背景。如果您的图像具有白色背景,那么您可以尝试使用globalCompositeOperations之一来仅绘制暗像素并忽略白色。

我添加了一个键入颜色的功能。您可以键入图像的颜色并在运行动画之前保存它。

var ctx = document.getElementById("can").getContext('2d');
var sprite = document.getElementById("sprite");
var sprite_width = 100;
var sprite_height = 100;
var sprite_frames = 10;
var sprite_frame = -1;
var sprite_x = 100;
var sprite_y = 0;
var sprite_fps = 10;
var sprite_time = 0;

var spriteCan = document.getElementById('spriteCan');
var sprites = [];

function makeSpriteCan() {
  var can = spriteCan;
  var ctx = can.getContext('2d');
  ctx.fillStyle="#FF00FF";
  ctx.fillRect(0,0,can.width,can.height);
  ctx.textAlign = "center";
  ctx.textBaseline='middle';
  ctx.font = "30pt Sans-serif";
  ctx.fillStyle="#FFFFFF";
  for (var i = 0; i < 10; i++) {
    ctx.fillText(i, 50 + i * 100, 50);
  }
  
}

makeSpriteCan();
spriteCan = keyColor(spriteCan, 255,0,255);
sprites.push(spriteCan);
ani();


function spriteLoad() {
  sprites.unshift(sprite)
}


function ani() {
  var now_time = Date.now();
  if (now_time - sprite_time > 1000 / sprite_fps) {
    sprite_time = now_time;
    sprite_frame ++;
    sprite_frame %= sprite_frames;
  }
  
  ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);

  var frame_x = sprite_frame * sprite_width;
  var frame_y = 0;

  
  for (var i = 0; i < sprites.length; i++) {
    ctx.drawImage(sprites[i], frame_x, frame_y, sprite_width, sprite_height, sprite_x, sprite_y, sprite_width, sprite_height);
  }
  
  
  requestAnimationFrame(ani);
}


// key out a color in an image
function keyColor(img, r, g, b) {
  var can = document.createElement('canvas');
  var ctx = can.getContext('2d');
  can.width=img.width;
  can.height=img.height;
  ctx.drawImage(img, 0, 0);
  var imageData = ctx.getImageData(0,0,can.width,can.height);
  var d = imageData.data;
  var length = d.length;
  
  for (var i = 0; i < length; i+=4) {
     if (d[i] == r && d[i+1] == g && d[i+2] == b) {
         d[i+3] = 0;
     }; 
  }
  ctx.putImageData(imageData, 0, 0);
  return can;
}
#can {
  border:1px solid red;
  background-color:black;
}
<img src="http://blocksjs.com/demos/block/images/coin.png" id="sprite" onload="spriteLoad()"/>
<canvas id="spriteCan" width="1000" height="100"></canvas>
<canvas id="can" width="300" height="100"></canvas>