Sunday, 15 June 2014

javascript - Moving an object around on dynamic canvas -



javascript - Moving an object around on dynamic canvas -

there plenty of questions how move objects around in first place, different: suppose (obviously) want object go "in front" of background, , background beingness changed/generated time. therefore, when move object 1 place another, want have been generated if object wasn't blocking appear before. how should handle this? should maintain record of "what have been generated" object , plop on when moves, or there less annoying way around this?

canvas has drawing setting want !

you can utilize canvas context's globalcompositeoperation.

this allows move "front" image on top of "background-changing" image.

here code , 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>

javascript html canvas

No comments:

Post a Comment