围绕其中心旋转随机角度的Canvas对象,以跟随mousemove的方向

时间:2016-06-20 13:40:47

标签: javascript canvas rotation

按照之前的回答问题Rotate a Canvas object around its center following mousemove event,在编写代码时,我陷入了另一个挑战。我想要一个内部有一个较小的彩色/黑色圆圈的圆圈。黑色圆圈的中心不在大圆圈的中心,而是稍微偏移。

假设我的对象在画布上以随机角度出现,当我在画布上移动鼠标时,我希望大圆圈的黑色圆圈部分始终面向我的鼠标方向,我不知道如何经过几个小时修改我的代码后实现。

这是我的代码(另见Fiddle:random-angled object rotate around center on mousemove):

ptr

使用解决方案进行更新:

在阅读@ K3N和@ markE的答案后,我找到了一个适合我的代码的解决方案,使用~int方法。虽然我使用int但我无法从constructvar canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); canvas.width = window.innerWidth; canvas.height = window.innerHeight; class Circle { constructor(options) { this.cx = options.x; this.cy = options.y; this.radius = options.radius; this.color = options.color; this.angle = options.angle; this.toAngle = this.angle; this.binding(); } binding() { const self = this; window.addEventListener('mousemove', (e) => { self.update(e.clientX, e.clientY); }); } update(nx, ny) { this.toAngle = Math.atan2(ny - this.cy, nx - this.cx); } render() { ctx.clearRect(0,0,canvas.width,canvas.height); ctx.save(); ctx.beginPath(); ctx.lineWidth = 1; ctx.translate(this.cx, this.cy); if (this.toAngle !== this.angle) { ctx.rotate(this.toAngle - this.angle); } ctx.strokeStyle = this.color; ctx.arc(0, 0, this.radius, 0, Math.PI * 2); ctx.stroke(); ctx.closePath(); ctx.beginPath(); ctx.fillStyle = 'black'; ctx.arc(0, this.radius / 2, this.radius / 3, 0, Math.PI * 2); ctx.fill(); ctx.closePath(); ctx.restore(); } } var rotatingCircle = new Circle({ x: 340, y: 250, radius: 40, color: 'black', angle: Math.random() * 2 * Math.PI }); function animate() { rotatingCircle.render(); requestAnimationFrame(animate); } animate(); 中减去左侧和顶部,否则我的代码将失败。

以下是我目前实施的解决方案:

setTransform

0 个答案:

没有答案
相关问题