1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > 图片上传并进行裁剪

图片上传并进行裁剪

时间:2018-10-11 01:58:38

相关推荐

图片上传并进行裁剪

图片上传并进行裁剪

有一下几个功能

1:实现图片上传

2:实现图片预览

3:实现图片裁剪

使用到的知识

file对象,<input type='file'/>,cropper.js,

参考:https://fengyuanchen.github.io/cropperjs/

代码如下:

<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta http-equiv="x-ua-compatible" content="ie=edge"><meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"><title>Cropper.js</title><link rel="stylesheet" href="../css/cropper.css"><style>.container {margin: 20px auto;max-width: 640px;}img {max-width: 100%;}.cropper-view-box,.cropper-face {border-radius: 50%;}#image {width: auto;height: auto;}</style></head><body><div class="container"><label>上传图片:<input type='file' id="upImg" /></label><h1>裁剪图片</h1><div id='chooseImg'></div><h3>裁剪的结果</h3><p><button type="button" id="button">Crop</button></p><div id="result"></div></div><script src="../js/cropper.js"></script><script>var upImg = document.getElementById('upImg');//上传选择的文件upImg.addEventListener('change', function() {var objImage = '';objImage = upImg.files[0];var reader = new FileReader();reader.addEventListener('load', function() {var imgUrl = reader.result;var imgBox = document.getElementById('chooseImg');// 重新选择图片进行裁剪,如果裁剪的模块有内容,进行情况if (document.getElementById('image')) {imgBox.innerHTML = '';}//实现图片预览imageObj = document.createElement('img');imageObj.setAttribute('id', 'image');imageObj.src = imgUrl;imgBox.appendChild(imageObj);//选择后的图片进行裁剪cropperEvent(imageObj);});if (objImage) {reader.readAsDataURL(objImage);}}, false);function getRoundedCanvas(sourceCanvas) {var canvas = document.createElement('canvas');var context = canvas.getContext('2d');var width = sourceCanvas.width;var height = sourceCanvas.height;canvas.width = width;canvas.height = height;context.imageSmoothingEnabled = true;context.drawImage(sourceCanvas, 0, 0, width, height);context.globalCompositeOperation = 'destination-in';context.beginPath();context.arc(width / 2, height / 2, Math.min(width, height) / 2, 0, 2 * Math.PI, true);context.fill();return canvas;}function cropperEvent(image) {var button = document.getElementById('button');var result = document.getElementById('result');var croppable = false;var cropper = new Cropper(image, {aspectRatio: 1,viewMode: 1,ready: function() {croppable = true;},});button.onclick = function() {var croppedCanvas;var roundedCanvas;var roundedImage;if (!croppable) {return;}// CropcroppedCanvas = cropper.getCroppedCanvas();// RoundroundedCanvas = getRoundedCanvas(croppedCanvas);// ShowroundedImage = document.createElement('img');roundedImage.src = roundedCanvas.toDataURL();result.innerHTML = '';result.appendChild(roundedImage);};}</script></body></html></html>

实现效果:

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。