2
互聯網上有幾種工具可以使用JavaScript和PHP來裁剪圖像,但不幸的是,如果我們打算讓我們的應用程序嚴格脫機,那麼我們可以依賴的服務器端PHP腳本不需要這麼做,所以我們必須使用HTML5畫布和JavaScript以便離線裁剪圖像。我如何裁剪圖像使用HTML5畫布和JavaScript爲了離線裁剪圖像?
互聯網上有幾種工具可以使用JavaScript和PHP來裁剪圖像,但不幸的是,如果我們打算讓我們的應用程序嚴格脫機,那麼我們可以依賴的服務器端PHP腳本不需要這麼做,所以我們必須使用HTML5畫布和JavaScript以便離線裁剪圖像。我如何裁剪圖像使用HTML5畫布和JavaScript爲了離線裁剪圖像?
如果圖像來源於本地域,那麼您可以輕鬆地用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>
你可以寫'img.onload =作物;'而不是內聯函數。 – rvighne