Javascript 旋转后无法在图像上绘制它是在原始画布方向上绘制的

Javascript 旋转后无法在图像上绘制它是在原始画布方向上绘制的,javascript,html5-canvas,Javascript,Html5 Canvas,var c=document.getElementById(“画布”); var ctx=c.getContext(“2d”); var rw=1560; var-rh=2080; var cw=“null”; var lw=“null”; var lh=“null”; var fh=“空”; var-drag=false; var last_mousex=last_mousey=0; var mousex=mousey=0; var mousedown=false; var image=新图像

var c=document.getElementById(“画布”);
var ctx=c.getContext(“2d”);
var rw=1560;
var-rh=2080;
var cw=“null”;
var lw=“null”;
var lh=“null”;
var fh=“空”;
var-drag=false;
var last_mousex=last_mousey=0;
var mousex=mousey=0;
var mousedown=false;
var image=新图像();
image.src=”https://s3-us-west-2.amazonaws.com/s.cdpn.io/222579/darwin300.jpg"
image.onload=函数(e){
ctx.canvas.width=image.width;
ctx.canvas.height=image.height;
c、 宽度=图像宽度;
c、 高度=图像高度;
ctx.save();
如果(rw){
c、 宽度=相对湿度;
c、 高度=rw;
ctx.canvas.width=rh;
ctx.canvas.height=rw;
ctx.translate(相对湿度,0);
ctx.旋转((90*Math.PI)/180);
ctx.drawImage(图像,0,0,rw,rh);
ctx.save();
}
否则如果(lw){
c、 宽度=左侧;
c、 高度=lw;
ctx.canvas.width=lh;
ctx.canvas.height=lw;
翻译(lw-lh,lw);
ctx.旋转((-90*Math.PI)/180);
翻译(0,-(lw-lh));
ctx.drawImage(图像,0,0,lw,lh);
ctx.save();
}
否则如果(fh){
var maxsize=image.width;
var w=最大尺寸;
var比率=(image.width/w);
var h=(图像高度/比率);
c、 宽度=w;
c、 高度=h;
ctx.canvas.width=w;
ctx.canvas.height=h;
ctx.translate(w,h);
旋转(数学PI);
ctx.drawImage(图像,0,0,w,h);
ctx.save();
}
否则{
ctx.canvas.width=image.width;
ctx.canvas.height=image.height;
c、 宽度=图像宽度;
c、 高度=图像高度;
ctx.drawImage(图像,0,0);
ctx.save();
}
ctx.rect(200200550500);
ctx.strokeStyle=“绿色”;
ctx.lineWidth=“5”;
ctx.stroke();
};
函数drawrect(){
$(c).on('mousedown',函数(e){
last_mousex=parseInt((image.width/c.scrollWidth)*e.offsetX);
last_mousey=parseInt((image.height/c.scrollHeight)*e.offsetY);
rx=最后一个鼠标;
ry=最后一个鼠标;
mousedown=true;
});
$(c).on('mouseup',函数(e){
last_mousex=parseInt((image.width/c.scrollWidth)*e.offsetX);
last_mousey=parseInt((image.height/c.scrollHeight)*e.offsetY);
mousedown=false;
如果(!mousedown){
重新绘制(最后一个鼠标、最后一个鼠标、ctx);
}
});
$(c).on('mousemove',函数(e){
mousex=parseInt((image.width/c.scrollWidth)*e.offsetX);
mousey=parseInt((image.height/c.scrollHeight)*e.offsetY);
如果(鼠标向下){
变量宽度=mousex-last\u mousex;
变量高度=鼠标-最后一个鼠标;
}
});
}
功能重绘(tox、toy、ctx){
ctx.beginPath();
ctx.restore();
ctx.rect(rx,ry,tox-rx,toy-ry);
ctx.strokeStyle=“黑色”;
ctx.lineWidth=“3”;
ctx.stroke();
ctx.closePath();
xMi=rx;
yMi=ry;
xMa=tox-rx;
yMa=玩具Y;
}

问题是您使用.translate().rotate()方法变换了画布。尽管如此,这幅画仍然有效——它就在可见区域之外

要解决这个问题,您需要将转换重置为单位矩阵

只需插入:

ctx.setTransform(1, 0, 0, 1, 0, 0);

在onload回调函数的末尾。

使用ctx.setTransform(1,0,0,1,0,0),我当前绘制的画布矩形会发生更改。如果您不关心IE或旧的Edgecoordinates也会发生更改