問題描述
您好,當我移動鼠標時,我想圍繞它的中心旋轉這個形狀,但目前它正在圍繞 (0, 0) 旋轉.如何更改我的代碼?
Hi I want to rotate this shape around its center when I move my mouse, but currently it's rotating around (0, 0). How to change my code?
源代碼(另見jsfiddle):
var 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 = 0;
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;
if (this.toAngle !== this.angle) {
ctx.rotate(this.toAngle - this.angle);
}
ctx.strokeStyle = this.color;
ctx.arc(this.cx, this.cy, this.radius, 0, Math.PI * 2);
ctx.stroke();
ctx.closePath();
ctx.beginPath();
ctx.fillStyle = 'black';
ctx.fillRect(this.cx - this.radius / 4, this.cy - this.radius / 4, 20, 20);
ctx.closePath();
ctx.restore();
}
}
var rotatingCircle = new Circle({
x: 150,
y: 100,
radius: 40,
color: 'black'
});
function animate() {
rotatingCircle.render();
requestAnimationFrame(animate);
}
animate();
推薦答案
你需要:
- 首先平移到旋轉點(樞軸)
- 然后旋轉
- 然后:
- A:在 (0,0) 處繪制,使用 (-width/2, -height/2) 作為相對坐標(用于居中繪圖)
- B:向后平移并使用對象的絕對位置并減去相對坐標進行居中繪圖
修改后的代碼:
ctx.beginPath(); ctx.lineWidth = 1; ctx.translate(this.cx, this.cy); // translate to pivot 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); // render at pivot ctx.closePath(); // must come before stroke() btw. ctx.stroke(); ctx.beginPath(); ctx.fillStyle = 'black'; ctx.fillRect(-this.radius / 4, -this.radius / 4, 20, 20); // render at pivot
改良小提琴
額外提示:您當前正在使用
save()
/restore()
調用來維護轉換矩陣.另一種方法是使用最初替換save()
/restore()
的絕對值來設置矩陣 - 所以而不是第一個translate()
:Bonus tip: you're currently using
save()
/restore()
calls to maintain the transformation matrix. Another way could be to set the matrix using absolute values initially replacing thesave()
/restore()
- so instead of the firsttranslate()
:ctx.setTranform(1,0,0,1,this.cx, this.cy); // translate to pivot
您還可以為每個設置單獨設置樣式等內容.無論如何,它不會改變核心解決方案.
You can also set things like styles on an individual basis for each. Regardless, it doesn't change the core solution though.
這篇關于如何在鼠標移動事件后圍繞其中心旋轉 Canvas 對象?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!