html将已经旋转的图形剪切,如何使用HTML5画布获得旋转的图像裁剪

markE..

6

您可以使用临时画布剪辑和取消旋转蓝框

从图像中剪切蓝色矩形的边界框

取消旋转边界框,使蓝色矩形不旋转(角度== 0)

剪切额外的边界框区域以仅显示蓝色矩形

将蓝色矩形绘制到显示画布

yqVje.png

body{ background-color: ivory; }

canvas{border:1px solid red;}

$(function(){

var canvas=document.getElementById("canvas");

var ctx=canvas.getContext("2d");

// blue rect's info

var blueX=421;

var blueY=343;

var blueWidth=81;

var blueHeight=44;

var blueAngle=-25.00*Math.PI/180;

// load the image

var img=new Image();

img.οnlοad=start;

img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/temp6.jpg";

function start(){

// create 2 temporary canvases

var canvas1=document.createElement("canvas");

var ctx1=canvas1.getContext("2d");

var canvas2=document.createElement("canvas");

var ctx2=canvas2.getContext("2d");

// get the boundingbox of the rotated blue box

var rectBB=getRotatedRectBB(blueX,blueY,blueWidth,blueHeight,blueAngle);

// clip the boundingbox of the rotated blue rect

// to a temporary canvas

canvas1.width=canvas2.width=rectBB.width;

canvas1.height=canvas2.height=rectBB.height;

ctx1.drawImage(img,

rectBB.cx-rectBB.width/2,

rectBB.cy-rectBB.height/2,

rectBB.width,

rectBB.height,

0,0,rectBB.width,rectBB.height

);

// unrotate the blue rect on the temporary canvas

ctx2.translate(canvas1.width/2,canvas1.height/2);

ctx2.rotate(-blueAngle);

ctx2.drawImage(canvas1,-canvas1.width/2,-canvas1.height/2);

// draw the blue rect to the display canvas

var offX=rectBB.width/2-blueWidth/2;

var offY=rectBB.height/2-blueHeight/2;

canvas.width=blueWidth;

canvas.height=blueHeight;

ctx.drawImage(canvas2,-offX,-offY);

} // end start

// Utility: get bounding box of rotated rectangle

function getRotatedRectBB(x,y,width,height,rAngle){

var absCos=Math.abs(Math.cos(rAngle));

var absSin=Math.abs(Math.sin(rAngle));

var cx=x+width/2*Math.cos(rAngle)-height/2*Math.sin(rAngle);

var cy=y+width/2*Math.sin(rAngle)+height/2*Math.cos(rAngle);

var w=width*absCos+height*absSin;

var h=width*absSin+height*absCos;

return({cx:cx,cy:cy,width:w,height:h});

}

}); // end $(function(){});

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值