2013-02-15 2 views
0

처음부터 오브젝트를 움직이는 방법에 대해 많은 질문이 있지만 이는 다릅니다. 내 오브젝트를 배경의 "앞"으로 이동 시키려면 (분명히) 내 배경이 항상 변경되고/생성되고 있다는 것입니다. 따라서 개체를 한 위치에서 다른 위치로 이동할 때 개체가 이전 위치에 나타나지 않도록 개체를 차단하지 않으면 생성 된 개체를 원합니다. 어떻게해야합니까? 객체가있는 곳에서 "무엇이 생성되었을 것인가"에 대한 기록을 유지해야할까요? 아니면 움직일 때 그걸 포착 할 것인가?동적 캔버스에서 오브젝트 이동

+0

페이지상의 동일한 위치에 위치하는 두 개의 캔버스의 배경 및 전경을 갖는 고려 : 여기서

일부 코드 바이올린이다. – Tmdean

답변

1

캔버스에는 원하는대로 정확하게 그리기 설정이 있습니다!

캔버스 컨텍스트의 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> 
관련 문제