Javascript 如何在单个画布中旋转裁剪的图像

Javascript 如何在单个画布中旋转裁剪的图像,javascript,canvas,gsap,Javascript,Canvas,Gsap,我在画布中画了一幅图像,它被裁剪成4个不同的部分。我想旋转,例如,第二个裁剪区域围绕其最上面的边在中心。 现在,如果我更改translate值,旋转与之前相同,唯一的区别是posX,posY被更改 绘图功能: //Function that is called on each 'tick' event, 60fps draw: function(){ if(this.rotation != 0){ _self.elements.context.save();

我在画布中画了一幅图像,它被裁剪成4个不同的部分。我想旋转,例如,第二个裁剪区域围绕其最上面的边在中心。 现在,如果我更改
translate
值,旋转与之前相同,唯一的区别是
posX
posY
被更改

绘图功能:

//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});

我还提供了完整的代码,其中应该会让您更好地理解我所说的内容。

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

  • 在您的行中使用
    \u self.elements.context.drawImage(…
    调用
    \u self.CanvasImage
    对象内的
    函数,而不是传递
    this.dx
    this.dy
    ,尝试传递
    <0
    <0
  • 然后在你的self.elements.context.translate(…调用同一个函数中,传递
    this.dx
    this.dy
  • 这将使对象围绕其左上方的点旋转
  • 但是,如果要围绕其顶部中心移动 那么你能做的是同样的事情
    \u self.elements.context.drawImage(…
    调用上述调用,而不是传递
    0
    作为前一个调用的替换
    this.dx
    值,传递
    -(this.sw*0.5)
  • JS代码更新#1(针对上述第1-3点):

    JS代码更新#2(针对上述第4点):


    希望这有帮助。

    这是我一直在寻找的,谢谢@Tahir Ahmed!
    ...
    _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);
    ...
    
    ...
    _self.elements.context.drawImage(_self.elements.image, this.sx, this.sy, this.sw, this.sh, -(this.sw * 0.5), 0, this.sw, this.dh);
    ...