简体   繁体   中英

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

互联网上有几种工具可以使用 JavaScript 和 PHP 裁剪图像,但不幸的是,如果我们打算让我们的应用程序严格离线,则没有我们可以依赖的服务器端 PHP 脚本,因此要实现这一点,我们必须使用 HTML5 canvas 和 JavaScript 以便离线裁剪图像。

If the image originated on the local domain, then you can easily crop it with html canvas.

But, if the image originated from another domain, you will run into CORS security errors: http://code.google.com/p/html5security/wiki/CrossOriginRequestSecurity

If needed, you can also scale up/down as you are cropping.

Here's example code to use canvas' drawImage to crop an image:

<!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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM