互联网上有多种工具可以使用 JavaScript 和 PHP 裁剪图像,但不幸的是,如果我们打算让我们的应用程序严格离线,则没有可以依赖的服务器端 PHP 脚本,因此要实现这一点,我们必须使用 HTML5 Canvas 和 JavaScript 离线裁剪图像。
最佳答案
如果图像源自本地域,那么您可以使用 html canvas 轻松裁剪它。
但是,如果图像源自另一个域,您将遇到 CORS 安全错误:http://code.google.com/p/html5security/wiki/CrossOriginRequestSecurity
如果需要,您还可以在裁剪时放大/缩小。
以下是使用 canvas 的 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>
关于javascript - 如何使用 HTML5 Canvas 和 JavaScript 裁剪图像以离线裁剪图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16869923/