在动态画布上移动对象

时间:2013-02-15 18:56:50

标签: javascript html canvas

关于如何首先移动物体有很多问题,但这是不同的:假设我(显然)希望我的物体“在前面”背景,并且我的背景正在改变/一直生成。因此,当我将对象从一个地方移动到另一个地方时,如果对象没有阻止它出现在之前的位置,我想要生成的内容。我该怎么处理?我应该记录一下“物体会产生什么”的记录,并在物体移动时将其打开,还是有一种不那么烦人的方法可以解决这个问题?

1 个答案:

答案 0 :(得分:1)

Canvas有一个绘图设置,可以完全按照您的意愿进行操作!

您可以使用画布上下文的 globalCompositeOperation

这使您可以将“前”图像移到“背景变化”图像的顶部。

以下是一些代码和小提琴:http://jsfiddle.net/m1erickson/TrXB4/

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>

<style>
    body{ background-color: ivory; background-color:black; }
    canvas{border:1px solid red;}
</style>

<script>
    $(function(){

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");

var sun = new Image();
var moon = new Image();
var earth = new Image();
function init(){
  sun.src = 'http://cdn-img.easyicon.cn/png/36/3642.png';
  moon.src = 'http://openclipart.org/people/purzen/purzen_A_cartoon_moon_rocket.svg';
  earth.src = 'http://iconbug.com/data/26/256/e5b23e861bc9979da6c3d03b75862b7e.png';
  setInterval(draw,100);
}

function draw() {
  var ctx = document.getElementById('canvas').getContext('2d');

  ctx.globalCompositeOperation = 'destination-over';
  ctx.clearRect(0,0,350,350); // clear canvas

  ctx.fillStyle = 'rgba(0,0,0,0.4)';
  ctx.strokeStyle = 'rgba(0,153,255,0.4)';
  ctx.save();
  ctx.translate(150,150);

  // Earth
  var time = new Date();
  ctx.rotate( ((2*Math.PI)/60)*time.getSeconds() + ((2*Math.PI)/60000)*time.getMilliseconds() );
  ctx.translate(105,0);
  ctx.fillRect(0,-12,50,24); // Shadow
  ctx.drawImage(earth,-12,-12,48,48);

  // Moon
  ctx.save();
  ctx.rotate( ((2*Math.PI)/6)*time.getSeconds() + ((2*Math.PI)/6000)*time.getMilliseconds() );
  ctx.translate(0,28.5);
  ctx.drawImage(moon,-3.5,-3.5,16,32);
  ctx.restore();

  ctx.restore();

  ctx.beginPath();
  ctx.arc(150,150,105,0,Math.PI*2,false); // Earth orbit
  ctx.stroke();

  ctx.drawImage(sun,100,100,96,96);
}

    init();    

    }); // end $(function(){});
</script>

</head>

<body>

<canvas id="canvas" width=350 height=350></canvas>


</body>
</html>
相关问题