2013-06-01 67 views

回答

2

如果圖像來源於本地域​​,那麼您可以輕鬆地用html canvas對其進行裁剪。

但是,如果圖像源自另一個域,你會遇到CORS安全錯誤:http://code.google.com/p/html5security/wiki/CrossOriginRequestSecurity

如果需要的話,您也可以按比例向上/向下因爲你是裁剪。

這裏的示例代碼使用畫布drawImage裁剪圖像:

<!doctype html> 
<html> 
<head> 
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css --> 
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script> 

<style> 
    body{ background-color: ivory; } 
    canvas{border:1px solid red;} 
</style> 

<script> 
$(function(){ 

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

    var img=new Image(); 
    img.onload=function(){ 
     crop(); 
    } 
    img.src=document.getElementById("source").src; 

    function crop(){ 
     // this takes a 105x105px crop from img at x=149/y=4 
     // and copies that crop to the canvas 
     ctx.drawImage(img,149,4,105,105,0,0,105,105); 
     // this uses the canvas as the src for the cropped img element 
     document.getElementById("cropped").src=canvas.toDataURL(); 
    } 

}); // end $(function(){}); 
</script> 

</head> 

<body> 
    <img id="source" width=400 height=234 src="localImage.png"> 
    <img id="cropped" width=105 height=105> 
    <canvas id="canvas" width=105 height=105></canvas> 
</body> 
</html> 
+0

你可以寫'img.onload =作物;'而不是內聯函數。 – rvighne