清除Javascript中的drawImage()函数

时间:2019-01-30 03:00:23

标签: javascript html css canvas drawimage

如何获取画布以清除前一个图像,使其看起来像我的角色正在移动?现在,它显示了我角色在屏幕上移动时的每个动画。我在下面贴了一张图片。

这是我的Javascript

function update(){
var imageObj = new Image();
if(fr1){
imageObj.src = 'https://i.ibb.co/yhbRD1R/Mega1.png';
}

if(fr2){
imageObj.src = 'https://i.ibb.co/S74hLKX/Mega2.png';
}
if(fr3){
imageObj.src = 'https://i.ibb.co/tC1j7wC/Mega3.png';
}
if(fr4){
imageObj.src = 'https://i.ibb.co/Tr2cqH9/Mega4.png';
}
if(fr5){
imageObj.src = 'https://i.ibb.co/jvr49xx/Mega5.png';
}

if(fr6){
imageObj.src = 'https://i.ibb.co/BrQnPNR/Mega6.png';
}
if(fr7){
imageObj.src = 'https://i.ibb.co/CJdzqGR/Mega7.png';
}
if(fr8){
imageObj.src = 'https://i.ibb.co/frbN0Dj/Mega8.png';
}
if(fr9){
imageObj.src = 'https://i.ibb.co/RjLL6z1/Mega9.png';
}
if(fr10){
imageObj.src = 'https://i.ibb.co/2ypxYjw/Mega10.png';
}
var canvas= document.getElementById('canvas');
var context = canvas.getContext('2d');

image1.style.visibility="hidden";
imageObj.onload = function() {

context.drawImage(imageObj,mainx,mainy,100,100);
};

}

这是正在发生的事情:

Here is what's happening:

2 个答案:

答案 0 :(得分:1)

每次加载新图像时,您都可以使用context.clearRect(x, y, dx, dy)。另外,我通过将所有动画精灵放入一个数组中,然后使用frameCount % frames.length选择给定的帧,来简化了代码。 frameCount是一个变量,每个游戏循环(每次setInterval运行时)都会递增。因此,使用模运算符%可以将数字限制在数组的0length之间,从而允许您从frames数组中选择一个新的帧每次循环运行。

请参见下面的工作示例:

var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var mainx = 0;
var mainy = canvas.height/2;

var frames = ['https://i.ibb.co/yhbRD1R/Mega1.png',
'https://i.ibb.co/S74hLKX/Mega2.png',
'https://i.ibb.co/tC1j7wC/Mega3.png',
'https://i.ibb.co/Tr2cqH9/Mega4.png',
'https://i.ibb.co/jvr49xx/Mega5.png',
'https://i.ibb.co/BrQnPNR/Mega6.png',
'https://i.ibb.co/CJdzqGR/Mega7.png',
'https://i.ibb.co/frbN0Dj/Mega8.png',
'https://i.ibb.co/RjLL6z1/Mega9.png',
'https://i.ibb.co/2ypxYjw/Mega10.png'];

function update(fr) {
  var imageObj = new Image();
  imageObj.src = frames[fr];
  
  imageObj.onload = function() {
    context.clearRect(0, 0, canvas.width, canvas.height);
    context.drawImage(imageObj, mainx, mainy, 100, 100);
  };
  
  mainx = (mainx + 10) % canvas.width; // update position of character
  frameCount += 1; // update frame count to move to next image frame
}

var frameCount = 0;
setInterval(function() {
  update(frameCount % frames.length);
}, 100)
<canvas id="canvas" height="200" width="500" style="border: 1px solid black;"></canvas>

答案 1 :(得分:0)

尝试将context.clearRect(0, 0, canvas.width, canvas.height);放在context.drawImage(imageObj,mainx,mainy,100,100);之前。