旋转画布中的单个对象?

kat*_*tie 2 javascript canvas rotation

rotate()功能似乎旋转整个绘图区域。有没有办法单独旋转路径?我希望旋转的中心是对象,而不是绘图区域。

使用save()and restore()still 使旋转考虑整个绘图区域。

var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
context.save();
context.fillStyle = 'red';
context.rotate(0.35);
context.fillRect(40,40, 100, 100);
context.restore();

context.save();
context.fillStyle = 'blue';
context.rotate(0.35);
context.fillRect(200, 40, 100, 100);
context.restore();
Run Code Online (Sandbox Code Playgroud)
<canvas id="canvas" width="500" height="500"></canvas>
Run Code Online (Sandbox Code Playgroud)

Bli*_*n67 7

使用本地空间

他们不是在您想要的位置绘制对象,而是在其本地空间中围绕其自身原点绘制所有内容。原点位于 (0,0),是对象旋转的位置。

所以如果你有一个用来绘制的矩形

function drawRect(){
    context.fillRect(200, 40, 100, 100);
}
Run Code Online (Sandbox Code Playgroud)

更改它,使其在原点绘制

function drawRect(){
    context.fillRect(-50,-50 , 100, 100);
}
Run Code Online (Sandbox Code Playgroud)

现在您可以轻松地将其绘制到任何您想要的地方

从 setTransform 函数开始,因为它会清除任何现有的变换,并且是设置对象中心位置的便捷方法

ctx.setTransform(1,0,0,1,posX,posY); // clear transform and set center location 
Run Code Online (Sandbox Code Playgroud)

如果你想旋转它然后添加旋转

ctx.rotate(ang);
Run Code Online (Sandbox Code Playgroud)

并缩放

ctx.scale(scale,scale);
Run Code Online (Sandbox Code Playgroud)

如果您有两个不同的比例,您应该在旋转之前进行缩放。

现在只需调用绘图函数

drawRect();
Run Code Online (Sandbox Code Playgroud)

它以 posX 为中心绘制,posY 旋转并缩放。

您可以将它们全部组合成一个具有 x,y 位置、宽度和高度、比例和旋转的函数。您可以在 setTransform 中包含比例

function drawRect(x,y,w,h,scale,rotation){
   ctx.setTransform(scale,0,0,scale,x,y);
   ctx.rotate(rotation);
   ctx.strokeRect(-w/2,-h/2,w,h);
}
Run Code Online (Sandbox Code Playgroud)

它也适用于作为精灵的图像,我将包括一个 alpha

function drawImage(img,x,y,w,h,scale,rotation,alpha){
   ctx.globalAlpha = alpha;
   ctx.setTransform(scale,0,0,scale,x,y);
   ctx.rotate(rotation);
   ctx.drawImage(img,-img.width/2,-img.height/2,img.width,img.height);
}
Run Code Online (Sandbox Code Playgroud)

在一台已有 6 年历史的笔记本电脑上,可以在 Firefox 上每 1/60 秒绘制 2000 个精灵,每个精灵都旋转、缩放、定位并带有 alpha 淡入淡出。

无需费力来回翻译。只需将您绘制的所有对象保留在自己的原点周围,并通过变换移动该原点即可。

更新 丢失了演示,因此这里展示如何在实践中做到这一点。

只是绘制了许多旋转的、缩放的、平移的、字母矩形。

通过使用 setTransform,您可以避免保存和恢复,从而节省大量时间

function drawRect(){
    context.fillRect(200, 40, 100, 100);
}
Run Code Online (Sandbox Code Playgroud)