Home >Web Front-end >JS Tutorial >Implement image cropping function based on JavaScript
Image cropping function based on JavaScript
With the development of the Internet, pictures have become more and more important in our lives. In web development, we often encounter the need to crop images. This article will implement a simple image cropping function through JavaScript and attach a code example.
1. Technical preparation
Before implementing the image cropping function, we need to prepare the following technologies:
2. Page layout
First, we need to build a page structure to display pictures and add control buttons for cropping functions. The following is a simple sample code:
<!DOCTYPE html> <html> <head> <title>图片剪裁功能</title> <style> #container { width: 800px; margin: 0 auto; text-align: center; } canvas { border: 1px solid #000; margin-bottom: 20px; } button { padding: 10px; margin: 10px; font-size: 14px; } </style> </head> <body> <div id="container"> <canvas id="imageCanvas" width="600" height="400"></canvas> <button onclick="loadImage()">上传图片</button> <button onclick="cropImage()">剪裁图片</button> </div> <script src="script.js"></script> </body> </html>
In this sample code, we create a container (<div id="container">) to contain images and controls button. The image is displayed through the <code><canvas></canvas>
tag (<canvas id="imageCanvas"></canvas>
), and we added a ID to facilitate subsequent JavaScript code operations. 3. JavaScript to implement image cropping functionNext, we need to implement the image uploading and cropping function through JavaScript. The following is a simple sample code:
const imageCanvas = document.getElementById('imageCanvas'); const ctx = imageCanvas.getContext('2d'); let image = null; function loadImage() { const input = document.createElement('input'); input.type = 'file'; input.accept = 'image/*'; input.onchange = function(event) { const file = event.target.files[0]; const reader = new FileReader(); reader.onload = function(e) { const img = new Image(); img.onload = function() { ctx.clearRect(0, 0, imageCanvas.width, imageCanvas.height); ctx.drawImage(img, 0, 0, imageCanvas.width, imageCanvas.height); image = img; }; img.src = e.target.result; }; reader.readAsDataURL(file); }; input.click(); } function cropImage() { if (image) { const cropCanvas = document.createElement('canvas'); const cropCtx = cropCanvas.getContext('2d'); cropCanvas.width = 400; cropCanvas.height = 400; cropCtx.drawImage(image, 0, 0, cropCanvas.width, cropCanvas.height); const croppedImage = cropCanvas.toDataURL('image/jpeg'); window.open(croppedImage); } else { alert('请先上传图片'); } }
The above is the detailed content of Implement image cropping function based on JavaScript. For more information, please follow other related articles on the PHP Chinese website!