In order to enable users to customize personal avatars, it is necessary to provide a screenshot function of uploaded pictures. Currently, many websites, especially SNS websites, provide such a function, which is very practical. There are two main forms of implementation, one is flash screenshots, and the other is javascript screenshots. Both methods have their own pros and cons. Regarding Flash screenshots, you can refer to the avatar upload function in the UcHome program, but this is not the topic I want to discuss. My main focus here is how to implement javascript screenshots, using jQuery's imgAreaSelect plug-in to easily implement the custom avatar [avatar] javascript screenshot function.
1. Preparation:
Two JS files
1. jquery.js download: jquery.js
2. jquery.imgareaselect.js Download: jquery.imgareaselect.js[imgareaselect-0.6.2.zip]
2. Use
function preview(img, selection){ var scaleX = 100 / selection.width; var scaleY = 100 / selection.height;
//Dynamic avatar Get the width, height, left border, and right border of the currently selected box
$('#biuuu + div > img').css({ width: Math.round(scaleX * 400) + 'px', height: Math.round(scaleY * 300) + 'px', marginLeft: '-' + Math.round(scaleX * selection.x1) + 'px', marginTop: '-' + Math.round(scaleY * selection.y1) + 'px' }); }
//Load small avatar
$(document).ready(function () { $('<div><img src="biuuu.jpg" style="position: relative;" /></div>') .css({ float: 'left', position: 'relative', overflow: 'hidden', width: '100px', height: '100px' }) .insertAfter($('#biuuu')); });
//Initial loading
$(window).load(function () { $('#biuuu').imgAreaSelect({ aspectRatio: '1:1', onSelectChange: preview }); });
Three, call
<div class="container"> <p> <img id="biuuu" src="biuuu.jpg" title="biuuu" style="float: left; margin-right: 10px;" /> </p> </div>
Using the above javascript screenshot to expand can achieve many dynamic functions. The imgAreaSelect plug-in provided by jQuery is very simple to call. For other related applications, please refer to: imgAreaSelect Examples
It is very simple to use the jQuery plug-in imgAreaSelect to implement javascript screenshots. It is basically a dynamic image display, obtaining the position of the source image and the size of the selection box [width and height], and easily realizing the javascript screenshot function.