2014-09-26 112 views
0

我使用的圖像大小爲1024 x 768,並且我的圖像大小爲300 x 300,因此我想先將圖像大小調整爲300 x 300,然後在畫布內旋轉它比例。 我正在使用下面的代碼,但它正在調整圖像大小,但旋轉畫布外的一些元素。所以,如果你點擊右鍵,那麼你什麼都看不到,然後再次右擊,然後你將圖像向下旋轉。圖像調整大小然後在畫布中旋轉 - javascript

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(); 
}); 

請檢查我的代碼中的jsfiddle以及 http://jsfiddle.net/6ZsCz/914/

回答

0

嘗試這種變化。

  • 轉換到畫布的中心。
  • 帶有[x,y]偏移量的ImageImage的DrawImage image.width/2 & image.height/2。此偏移量是必需的,因爲平移有效地使畫布中心點[150,150]成爲新的畫布原點[0,0]。您需要負向偏移量將圖形向左和向上拉動以補償新原點。

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"; 
 

 

 
$("#clockwise").click(function(){ 
 
    degrees+=90 
 
    ctx.clearRect(0,0,canvas.width,canvas.height); 
 
    ctx.save(); 
 
    ctx.translate(150,150); 
 
    ctx.rotate(degrees*Math.PI/180); 
 
    ctx.drawImage(image,0,0,image.width,image.height,-150,-150,300,300); 
 
    ctx.restore(); 
 
});
body{ background-color: ivory; } 
 
canvas{border:1px solid red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
 
<canvas id="canvas" width=300 height=300></canvas><br> 
 
<button id="clockwise">Rotate right</button>