0

そもそもオブジェクトを移動する方法についてはたくさんの質問がありますが、これは異なります。オブジェクトを背景の「前」に配置したいとし、背景がすべて変更/生成されているとします。時間。したがって、オブジェクトをある場所から別の場所に移動するときに、オブジェクトがオブジェクトをブロックしていなかった場合に生成されたものを、以前の場所に表示したいと思います。これをどのように処理すればよいですか?オブジェクトがどこにあるかを「何が生成されたか」を記録し、オブジェクトが移動したときにそれを配置する必要がありますか、それともこれを回避するための煩わしくない方法がありますか?

4

1 に答える 1

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>
于 2013-02-15T22:51:38.200 に答える