图像调整大小,然后在画布中旋转-javascript

图像调整大小,然后在画布中旋转-javascript,javascript,jquery,canvas,rotation,Javascript,Jquery,Canvas,Rotation,我使用的图像大小为1024x768,画布大小为300x300,因此我想先将图像大小调整为300x300,然后在画布内按比例旋转图像。 我正在使用下面的代码,但它正在调整图像的大小,但在画布外旋转一些元素。因此,如果你点击右键,你看不到任何东西,然后再次点击右键,你将看到向下旋转的图像 var canvas=document.getElementById("canvas"); var ctx=canvas.getContext("2d"); var degrees=0; var image=doc

我使用的图像大小为1024x768,画布大小为300x300,因此我想先将图像大小调整为300x300,然后在画布内按比例旋转图像。 我正在使用下面的代码,但它正在调整图像的大小,但在画布外旋转一些元素。因此,如果你点击右键,你看不到任何东西,然后再次点击右键,你将看到向下旋转的图像

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var degrees=0;
var image=document.createElement("img");
image.onload=function(){
    ctx.drawImage(image,0,0,300,300);
}
image.src="http://media1.santabanta.com/full1/Outdoors/Landscapes/landscapes-275a.jpg";
image.width = 300;
image.height = 300;
 $("#clockwise").click(function(){
     degrees+=90
     ctx.clearRect(0,0,canvas.width,canvas.height);
     ctx.save();
     ctx.translate(300,300);
     ctx.rotate(degrees*Math.PI/180);
     ctx.drawImage(image,0,0,300,300);
     ctx.restore();
});
请检查我在JSFIDLE中的代码 试试这个变体

平移到画布的中心。 [x,y]偏移量为image.width/2和image.height/2的DrawImage。此偏移是必需的,因为平移有效地使画布中心点[150150]成为新的画布原点[0,0]。需要负偏移来向左和向上拉动图形,以补偿新原点。 var canvas=document.getElementByIdcanvas; var ctx=canvas.getContext2d; 变量度=0; var image=document.createElementimg; image.onload=函数{ ctx.drawImageimage,0,0300300; } image.src=http://media1.santabanta.com/full1/Outdoors/Landscapes/landscapes-275a.jpg; $s.clickfunction{ 度+=90度 ctx.clearRect0,0,canvas.width,canvas.height; ctx.save; ctx.translate150150; ctx.rotatedgrees*Math.PI/180; ctx.drawImageimage,0,0,image.width,image.height,-150,-150300300; ctx.restore; }; 正文{背景色:象牙;} 画布{边框:1px纯红;} 右转