简体   繁体   中英

Rotate triangle around circle (2D)

I'm trying to rotate a triangle around a circle, the triangle should always face outwards, meaning it should rotate around the circle, AND around its center I'm guessing. I found this question, which is something like what I need, but just in reverse. Another thing I need is to have the triangle pointed at the user's mouse coords. aka the triangle is something like an arrow.

I just edited the code you linked and replaced the rectangle with a triangle, and animate() with a mouse move listener, of course:

 var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var cx = 100; var cy = 100; var radious = 10; var gap = 5; var triangleHeight = 25; var triangleBase = 10; redraw(cx + 1, cy); function redraw(mx, my) { mox = mx-cx; moy = my-cy; rotation = Math.atan2(moy, mox); ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.beginPath(); ctx.arc(cx, cy, radious, 0, Math.PI * 2); ctx.closePath(); ctx.fill(); ctx.save(); ctx.translate(cx, cy); ctx.rotate(rotation); ctx.beginPath(); ctx.moveTo(radious+gap, -triangleBase/2); ctx.lineTo(radious+gap, triangleBase/2); ctx.lineTo(radious+gap+triangleHeight, 0); ctx.lineTo(radious+gap, -triangleBase/2) ctx.stroke(); ctx.restore(); } canvas.addEventListener("mousemove", function (e) { redraw(e.pageX, e.pageY); }, false);
 <canvas id="canvas"></canvas>

BTW, it's my very first piece of code in JS, so, feel free to correct my code if something is funny.

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