简体   繁体   中英

Moving an object around on dynamic canvas

There are plenty of questions about how to move objects around in the first place, but this is different: suppose that I (obviously) want my object to go "in front" of the background, and that my background is being changed/generated all the time. Therefore, when I move the object from one place to another, I want what would have been generated if the object wasn't blocking it to appear where it was before. How should I handle this? Should I keep a record of "what would have been generated" where the object is and plop it on when it moves, or is there a less annoying way to get around this?

Canvas has a drawing setting to do exactly what you want !

You can use the canvas context's globalCompositeOperation .

This allows you to move your "front" image on top of your "background-changing" image.

Here is some code and a Fiddle: 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM