【问题标题】:How to rotate cropped images in single canvas如何在单个画布中旋转裁剪的图像
【发布时间】:2015-07-06 23:58:25
【问题描述】:

我在画布内绘制了一个图像,它被裁剪成 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 中提供了完整的代码,这应该可以更好地理解我在说什么。

【问题讨论】:

    标签: javascript canvas gsap


    【解决方案1】:

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

    1. _self.elements.context.drawImage(... 对象内调用 draw 函数,而不是传递 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

    希望这会有所帮助。

    【讨论】:

    • 这就是我要找的,谢谢@Tahir Ahmed!
    猜你喜欢
    • 1970-01-01
    • 2013-04-05
    • 2014-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-30
    • 1970-01-01
    相关资源
    最近更新 更多