如何在单个 canvas 中旋转裁剪后的图像

How to rotate cropped images in single canvas

我在 canvas 中绘制了一张图像,它被裁剪成 4 个不同的部分。例如,我想围绕其中心的最顶部旋转第二个裁剪区域。 现在,如果我更改 translate 值,旋转与以前相同,唯一不同的是 posXposY 已更改。

绘图函数:

//Function that is called on each 'tick' event, 60fps
draw: function(){
    if(this.rotation != 0){
        _self.elements.context.save();      
        // what values to put here so that '2' would rotate correctly ???
        _self.elements.context.translate(0,0);      
        _self.elements.context.rotate(this.rotation);
        _self.elements.context.drawImage(
            _self.elements.image,this.sx, this.sy, this.sw, this.sh, this.dx, this.dy, this.sw, this.dh
        );
        _self.elements.context.restore();
    }else{
        _self.elements.context.drawImage(
            _self.elements.image, this.sx, this.sy, this.sw, this.sh, this.dx, this.dy, this.sw, this.dh
        );
    }
}

使用 TweenMax 旋转

//Rotate the '2' cropped image part   
TweenMax.to(_self.CanvasImages.collection[1], 2, {rotation:0.5});

我还在 jsFiddle 中提供了完整的代码,应该可以让您更好地理解我在说什么。

如果我能够正确理解这一点,我认为您可以这样做:

  1. _self.elements.context.drawImage(... 行中,在 draw 函数中调用 _self.CanvasImage 对象,而不是传递 this.dxthis.dy,尝试传递 00.
  2. 然后在您的 _self.elements.context.translate(... 调用同一函数内,传递 this.dxthis.dy.
  3. 这应该围绕其 top-left 点旋转对象。
  4. 但是,如果您想将其移动到 top-center 点附近 那么你能做的就是在同一个 上面提到的 _self.elements.context.drawImage(... 调用,而不是传递 0 作为对前面的替换 this.dx值,传-(this.sw * 0.5).

JS 代码更新#1(对于上面的第 1-3 点):

...
_self.elements.context.translate(this.dx, this.dy);
_self.elements.context.rotate(this.rotation);
_self.elements.context.drawImage(_self.elements.image, this.sx, this.sy, this.sw, this.sh, 0, 0, this.sw, this.dh);
...

jsFiddle #1.

JS 代码更新 #2(对于上面的第 4 点):

...
_self.elements.context.drawImage(_self.elements.image, this.sx, this.sy, this.sw, this.sh, -(this.sw * 0.5), 0, this.sw, this.dh);
...

jsFiddle #2.

希望这对您有所帮助。