HTML5 有很多好玩的特性,本实验利用 HTML5 的 canvas 技术,结合 HTML5 的 File API 来实现图片的本地裁剪,从一个大图片中选取裁剪区域,保存等功能。
1.创建HTML文件和CSS样式
在本demo中,前端样式做的较为简单,所以二者写在了一个文件中。
index.html
<!DOCTYPE html>
<html>
<head>
<title>HTML5 Crop Image</title>
</head>
<style type="text/css">
body {
text-align: center;
}
#label {
border: 1px solid #ccc;
background-color: #fff;
text-align: center;
height: 300px;
width: 300px;
margin: 20px auto;
position: relative;
}
#get_image {
position: absolute;
}
#edit_pic {
position: absolute;
display: none;
background: #000;
}
#cover_box {
position: absolute;
z-index: 9999;
display: none;
top: 0px;
left: 0px;
}
#show_edit {
margin: 0 auto;
display: inline-block;
}
#show_pic {
height: 100px;
width: 100px;
border: 2px solid #000;
overflow: hidden;
margin: 0 auto;
display: inline-block;
}
</style>
<body>
<input type="file" name="file" id="post_file" />
<button id="save_button">SAVE</button>
<div id="label">
<canvas id="get_image"></canvas>
<p>
<canvas id="cover_box"></canvas>
<canvas id="edit_pic"></canvas>
</p>
</div>
<p>
<span id

这篇博客介绍了如何使用HTML5的canvas技术和FileAPI来实现在浏览器中对本地图片进行裁剪。首先创建HTML文件和CSS样式,设置好图片预览区域和裁剪框。然后通过FileReader读取用户上传的图片,并在canvas上绘制。接着实现拖动裁剪框以调整裁剪区域,并在用户保存时,将裁剪后的图片绘制到新的canvas上,转换为base64编码显示在预览框中。整个过程详细讲解了图片裁剪的实现步骤,包括图片等比例缩放、裁剪区域的移动和调整、以及裁剪结果的保存。
最低0.47元/天 解锁文章
4602

被折叠的 条评论
为什么被折叠?



