我正在尝试创建一个JavaScript对象,该对象具有一个方法,允许矩形在rAF回调期间围绕其自己的原点旋转。
我做的事情:计算对象的来源……
而不是绘制rects (this.x, this.y) 您可以在0,0处绘制它们并将它们转换为 (this.x, this.y) ;
(this.x, this.y)
// author: Nicholas Fazzolari var canvas = document.querySelector('canvas'); var ctx = canvas.getContext('2d'); canvas.width = window.innerWidth; canvas.height = window.innerHeight; var xCenterCanvas = innerWidth/2; var yCenterCanvas = innerHeight/2; // custom rectangle object function RectangleCustom(x, y, w, h, color) { this.w = w; this.h = h; this.x = x; this.y = y; this.color = color; this.radians = (Math.PI/180) * 2; // change the last value to change speed this.rotation = 0; // draws a rectangle at given coordinates this.draw = function() { this.rotation += this.radians; ctx.save(); ctx.fillStyle = this.color; ctx.translate(this.x, this.y); ctx.rotate(this.rotation); ctx.fillRect(0,0, this.w, this.h); ctx.restore(); } this.update = function() { // animation updates } } // singleton rectangles var bkgRectangle = new RectangleCustom(0, 0, innerWidth, innerHeight, "#212121"); var redRectangle = new RectangleCustom(xCenterCanvas - 64, yCenterCanvas - 64, 128, 128, "#F44336"); // main animation loop function mainAnimationLoop() { // runs animation and clears the canvas each call requestAnimationFrame(mainAnimationLoop); ctx.clearRect(0, 0, innerWidth, innerHeight); bkgRectangle.draw(); redRectangle.draw(); } mainAnimationLoop();
<canvas></canvas>