有人能告诉我如何在画布内移动图像吗?

时间:2015-07-23 19:54:41

标签: javascript canvas

有人能告诉我如何让画布上的图像移动吗?在游戏的先前版本中,我制作的图像是一个div,所以它移动得很好,但我无法弄清楚这一点。它让我写得更多,所以请忽略这一部分:



//this is the variable for the image i want to move
var blinky = {
x: 0,
y: 0
};






//this makes the image only appear when the page is loaded
var byReady = false;
var byImage = new Image();
byImage.onload = function(){
	byReady = true;
};

byImage.src = "blinky.jpg"





//this puts the images on the canvas
var render = function(){
if(bgReady){
ctx.drawImage(bgImage,0,0);
}

if(hrReady){
ctx.drawImage(hrImage,hero.x, hero.y);
}

if(emReady){
ctx.drawImage(emImage,monster.x, monster.y);
}

if(byReady){
	ctx.drawImage(byImage,blinky.x,blinky.y);
}







//this moves a div around the screen randomly
$(document).ready(function(){
    animateDiv();
    
});

function makeNewPosition(){
    
    // Get viewport dimensions (remove the dimension of the div)
    var h = $(window).height() - 30;
    var w = $(window).width() - 30;
    
    var nh = Math.floor(Math.random() * h);
    var nw = Math.floor(Math.random() * w);
    
    return [nh,nw];    
    
}

function animateDiv(){
    var newq = makeNewPosition();
    var oldq = $('#blinky').offset();
    var speed = calcSpeed([oldq.top, oldq.left], newq);
    
    $('#blinky').animate({ top: newq[0], left: newq[1] }, speed, function(){
      animateDiv();        
    });
    
};

function calcSpeed(prev, next) {
    
    var x = Math.abs(prev[1] - next[1]);
    var y = Math.abs(prev[0] - next[0]);
    
    var greatest = x > y ? x : y;
    
    var speedModifier = 0.1;

    var speed = Math.ceil(greatest/speedModifier);

    return speed;

}




1 个答案:

答案 0 :(得分:0)

基本上你需要一个绘制循环(使用requestAnimationFrame)来绘制画布上下文中的图像。

这是一个完整的jsfiddle:http://jsfiddle.net/ety656yq/