我如何使用HTML5画布和JavaScript裁剪图像,以便离线裁剪图像

How can i crop image using the HTML5 canvas and JavaScript in order to crop an image offline?

本文关键字:图像 裁剪 离线 JavaScript 何使用 HTML5      更新时间:2023-09-26

互联网上有几个工具可以使用JavaScript和PHP裁剪图像,但不幸的是,如果我们打算让我们的应用程序严格脱机,那么我们就没有服务器端PHP脚本可以依赖,所以要实现这一点,我们必须使用HTML5画布和JavaScript来脱机裁剪图像

如果图像起源于本地域,那么您可以轻松地使用html画布裁剪它

但是,如果图像来自另一个域,您将遇到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>