javascript - How to rotate 2 rectangles in a canvas at the same time? -
i know can utilize "translate-rotate-translate back-fillrect" procedure rotate 1 single rectangle.
however, if want rotate them both @ same time , have timeinterval() create them rotate automatically every second?
i tried save , restore each time seek draw, didn't work.
you appear on right track!
save translate(rectx,recty) rotate fillrect(-rectwidth/2,-rectheight/2,rectwidth,rectheight) // draws rect w/ center rotation restorefor multiple rectangles
if define rectangle objects this:
var rects=[]; rects.push({x:50,y:50,w:50,h:35,color:'green',angle:0}); rects.push({x:150,y:120,w:30,h:20,color:'blue',angle:0});
then can set them in animation frame this:
requestanimationframe(animate); function animate(time){ // phone call loop in animation requestanimationframe(animate); // clear canvas , redraw rects ctx.clearrect(0,0,cw,ch); for(var i=0;i<rects.length;i++){ // draw rect @ specified angle var rect=rects[i]; ctx.save(); ctx.translate(rect.x+rect.w/2,rect.y+rect.h/2); ctx.rotate(rect.angle); ctx.fillstyle=rect.color; ctx.fillrect(-rect.w/2,-rect.h/2,rect.w,rect.h); ctx.restore(); // increment rect's angle next time rect.angle+=(math.pi*2)/60; } }
requestanimationframe
loops @ 60fps if increment rect's angle in each loop (math.pi*2)/60 rotate rect 1 total turn every second.
example code , demo:
class="snippet-code-js lang-js prettyprint-override">var canvas=document.getelementbyid("canvas"); var ctx=canvas.getcontext("2d"); var cw=canvas.width; var ch=canvas.height; var rects=[]; rects.push({x:50,y:50,w:50,h:35,color:'green',angle:0}); rects.push({x:150,y:120,w:30,h:20,color:'blue',angle:0}); requestanimationframe(animate); function animate(time){ // phone call loop in animation requestanimationframe(animate); // clear canvas , redraw rects ctx.clearrect(0,0,cw,ch); for(var i=0;i<rects.length;i++){ // draw rect @ specified angle var rect=rects[i]; ctx.save(); ctx.translate(rect.x+rect.w/2,rect.y+rect.h/2); ctx.rotate(rect.angle); ctx.fillstyle=rect.color; ctx.fillrect(-rect.w/2,-rect.h/2,rect.w,rect.h); // orientation symbol ctx.fillstyle='red'; ctx.fillrect(-rect.w/2,-rect.h/2,5,5) ctx.restore(); // increment rect's angle next time rect.angle+=(math.pi*2)/60; } } function drawrect(rect){ ctx.save(); ctx.translate(rect.x+rect.w/2,rect.y+rect.h/2); ctx.rotate(rect.angle); ctx.fillstyle=rect.color; ctx.fillrect(-rect.w/2,-rect.h/2,rect.w,rect.h); ctx.restore(); rect.angle+=deltaangle; }
class="snippet-code-css lang-css prettyprint-override">body{ background-color: ivory; } canvas{border:1px solid red;}
class="snippet-code-html lang-html prettyprint-override"><canvas id="canvas" width=300 height=300></canvas>
javascript jquery html css canvas
No comments:
Post a Comment