【问题标题】:HTML5 rotating canvas imageHTML5 旋转画布图像
【发布时间】:2013-10-25 11:43:56
【问题描述】:

我希望允许用户旋转画布,如果旋转后不再适合,则更改尺寸,这是一个小提琴:

http://jsfiddle.net/6ZsCz/84/

我似乎无法确定转换后的 x/y 位置:

ctx.translate(canvas.width/2,canvas.height/2);

如您所见,图像确实会旋转,但是当它向左/向右旋转时它会离开画布,我如何压缩高度以强制它留在边框中,这是我想要实现的示例旋转。

编辑:

因为这个问题似乎很受欢迎,所以我在这里发布解决方案而不是 JSFiddle

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var angleInDegrees=0;
var image=document.createElement("img");
image.onload=function(){
    ctx.drawImage(image,(canvas.width - image.width) / 2, (canvas.height - image.height) / 2,image.width, image.height);//ctx.drawImage(img, x, y, width, height)
}
image.src="http://www.farmvertical.com/wp-content/uploads/2007/10/vertical_farm_v2.jpg";
$("#clockwise").click(function(){ 
    angleInDegrees+=90;
    drawRotated(angleInDegrees);
});
$("#counterclockwise").click(function(){ 
    angleInDegrees-=90;
    drawRotated(angleInDegrees);
});
function drawRotated(degrees){
    ctx.clearRect(0,0,canvas.width,canvas.height);
    ctx.save();
    ctx.translate(canvas.width/2,canvas.height/2);
    ctx.rotate(degrees*Math.PI/180);

    if(angleInDegrees%180==0){
        ctx.drawImage(image, -image.width/2,-image.height/2);
    }else{
        ctx.drawImage(image, -image.width/2,-canvas.width/2,image.width, canvas.width);
    }
    ctx.restore();
}

【问题讨论】:

    标签: javascript html canvas


    【解决方案1】:

    这是你想要的吗?

    function drawRotated(degrees){
        ctx.clearRect(0,0,canvas.width,canvas.height);
        ctx.save();
        ctx.translate(canvas.width/2,canvas.height/2);
        ctx.rotate(degrees*Math.PI/180);
    
        if(angleInDegrees%180==0){
            ctx.drawImage(image, -image.width/2,-image.height/2);
        }else{
            ctx.drawImage(image, -image.width/2,-canvas.width/2,image.width, canvas.width);
        }
        ctx.restore();
    }
    

    【讨论】:

    • 是的!非常感谢!
    猜你喜欢
    • 2011-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-18
    • 2014-02-03
    • 2015-05-25
    • 2015-10-01
    • 1970-01-01
    相关资源
    最近更新 更多