This article mainly introduces the method of using JavaScript canvas to realize image cropping. Friends who need it can refer to it
canvas is a tag that allows us to use script drawing. It provides a complete series of attributes. and methods. We can use this to achieve graphics drawing, image processing and even simple animation and game production.
The canvas tag has only two attributes: width and height, which are used to set the width and height of the canvas. If not set through tag attributes or scripts, the default is 300*150;
Okay Okay, the introduction to canvas is here first. Let’s take a look at the code for cropping images using javascript combined with canvas:
var selectObj = null; function ImageCrop(canvasId, imageSource, x, y, width, height) { var canvas = $("#" + canvasId); if (canvas.length == 0 && imageSource) { return; } function canvasMouseDown(e) { StopSelect(e); canvas.css("cursor", "default"); } function canvasMouseMove(e) { var canvasOffset = canvas.offset(); var pageX = e.pageX || event.targetTouches[0].pageX; var pageY = e.pageY || event.targetTouches[0].pageY; iMouseX = Math.floor(pageX - canvasOffset.left); iMouseY = Math.floor(pageY - canvasOffset.top); canvas.css("cursor", "default"); if (selectObj.bDragAll) { canvas.css("cursor", "move"); canvas.data("drag", true); var cx = iMouseX - selectObj.px; cx = cx < 0 ? 0 : cx; mx = ctx.canvas.width - selectObj.w; cx = cx > mx ? mx : cx; selectObj.x = cx; var cy = iMouseY - selectObj.py; cy = cy < 0 ? 0 : cy; my = ctx.canvas.height - selectObj.h; cy = cy > my ? my : cy; selectObj.y = cy; } for (var i = 0; i < 4; i++) { selectObj.bHow[i] = false; selectObj.iCSize[i] = selectObj.csize; } // hovering over resize cubes if (iMouseX > selectObj.x - selectObj.csizeh && iMouseX < selectObj.x + selectObj.csizeh && iMouseY > selectObj.y - selectObj.csizeh && iMouseY < selectObj.y + selectObj.csizeh) { canvas.css("cursor", "pointer"); selectObj.bHow[0] = true; selectObj.iCSize[0] = selectObj.csizeh; } if (iMouseX > selectObj.x + selectObj.w - selectObj.csizeh && iMouseX < selectObj.x + selectObj.w + selectObj.csizeh && iMouseY > selectObj.y - selectObj.csizeh && iMouseY < selectObj.y + selectObj.csizeh) { canvas.css("cursor", "pointer"); selectObj.bHow[1] = true; selectObj.iCSize[1] = selectObj.csizeh; } if (iMouseX > selectObj.x + selectObj.w - selectObj.csizeh && iMouseX < selectObj.x + selectObj.w + selectObj.csizeh && iMouseY > selectObj.y + selectObj.h - selectObj.csizeh && iMouseY < selectObj.y + selectObj.h + selectObj.csizeh) { canvas.css("cursor", "pointer"); selectObj.bHow[2] = true; selectObj.iCSize[2] = selectObj.csizeh; } if (iMouseX > selectObj.x - selectObj.csizeh && iMouseX < selectObj.x + selectObj.csizeh && iMouseY > selectObj.y + selectObj.h - selectObj.csizeh && iMouseY < selectObj.y + selectObj.h + selectObj.csizeh) { canvas.css("cursor", "pointer"); selectObj.bHow[3] = true; selectObj.iCSize[3] = selectObj.csizeh; } if (iMouseX > selectObj.x && iMouseX < selectObj.x + selectObj.w && iMouseY > selectObj.y && iMouseY < selectObj.y + selectObj.h) { canvas.css("cursor", "move"); } // in case of dragging of resize cubes var iFW, iFH, iFX, iFY, mx, my; if (selectObj.bDrag[0]) { iFX = iMouseX - selectObj.px; iFY = iMouseY - selectObj.py; iFW = selectObj.w + selectObj.x - iFX; iFH = selectObj.h + selectObj.y - iFY; canvas.data("drag", true); } if (selectObj.bDrag[1]) { iFX = selectObj.x; iFY = iMouseY - selectObj.py; iFW = iMouseX - selectObj.px - iFX; iFH = selectObj.h + selectObj.y - iFY; canvas.data("drag", true); } if (selectObj.bDrag[2]) { iFX = selectObj.x; iFY = selectObj.y; iFW = iMouseX - selectObj.px - iFX; iFH = iMouseY - selectObj.py - iFY; canvas.data("drag", true); } if (selectObj.bDrag[3]) { iFX = iMouseX - selectObj.px; iFY = selectObj.y; iFW = selectObj.w + selectObj.x - iFX; iFH = iMouseY - selectObj.py - iFY; canvas.data("drag", true); } if (iFW > selectObj.csizeh * 2 && iFH > selectObj.csizeh * 2) { selectObj.w = iFW; selectObj.h = iFH; selectObj.x = iFX; selectObj.y = iFY; } drawScene(); } function canvasMouseOut() { $(canvas).trigger("mouseup"); } function canvasMouseUp() { selectObj.bDragAll = false; for (var i = 0; i < 4; i++) { selectObj.bDrag[i] = false; } canvas.css("cursor", "default"); canvas.data("select", { x: selectObj.x, y: selectObj.y, w: selectObj.w, h: selectObj.h }); selectObj.px = 0; selectObj.py = 0; } function Selection(x, y, w, h) { this.x = x; // initial positions this.y = y; this.w = w; // and size this.h = h; this.px = x; // extra variables to dragging calculations this.py = y; this.csize = 4; // resize cubes size this.csizeh = 6; // resize cubes size (on hover) this.bHow = [false, false, false, false]; // hover statuses this.iCSize = [this.csize, this.csize, this.csize, this.csize]; // resize cubes sizes this.bDrag = [false, false, false, false]; // drag statuses this.bDragAll = false; // drag whole selection } Selection.prototype.draw = function () { ctx.strokeStyle = '#666'; ctx.lineWidth = 2; ctx.strokeRect(this.x, this.y, this.w, this.h); // draw part of original image if (this.w > 0 && this.h > 0) { ctx.drawImage(image, this.x, this.y, this.w, this.h, this.x, this.y, this.w, this.h); } // draw resize cubes ctx.fillStyle = '#999'; ctx.fillRect(this.x - this.iCSize[0], this.y - this.iCSize[0], this.iCSize[0] * 2, this.iCSize[0] * 2); ctx.fillRect(this.x + this.w - this.iCSize[1], this.y - this.iCSize[1], this.iCSize[1] * 2, this.iCSize[1] * 2); ctx.fillRect(this.x + this.w - this.iCSize[2], this.y + this.h - this.iCSize[2], this.iCSize[2] * 2, this.iCSize[2] * 2); ctx.fillRect(this.x - this.iCSize[3], this.y + this.h - this.iCSize[3], this.iCSize[3] * 2, this.iCSize[3] * 2); }; var drawScene = function () { ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); // clear canvas // draw source image ctx.drawImage(image, 0, 0, ctx.canvas.width, ctx.canvas.height); // and make it darker ctx.fillStyle = 'rgba(0, 0, 0, 0.5)'; ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height); // draw selection selectObj.draw(); canvas.mousedown(canvasMouseDown); canvas.on("touchstart", canvasMouseDown); }; var createSelection = function (x, y, width, height) { var content = $("#imagePreview"); x = x || Math.ceil((content.width() - width) / 2); y = y || Math.ceil((content.height() - height) / 2); return new Selection(x, y, width, height); }; var ctx = canvas[0].getContext("2d"); var iMouseX = 1; var iMouseY = 1; var image = new Image(); image.onload = function () { selectObj = createSelection(x, y, width, height); canvas.data("select", { x: selectObj.x, y: selectObj.y, w: selectObj.w, h: selectObj.h }); drawScene(); }; image.src = imageSource; canvas.mousemove(canvasMouseMove); canvas.on("touchmove", canvasMouseMove); var StopSelect = function (e) { var canvasOffset = $(canvas).offset(); var pageX = e.pageX || event.targetTouches[0].pageX; var pageY = e.pageY || event.targetTouches[0].pageY; iMouseX = Math.floor(pageX - canvasOffset.left); iMouseY = Math.floor(pageY - canvasOffset.top); selectObj.px = iMouseX - selectObj.x; selectObj.py = iMouseY - selectObj.y; if (selectObj.bHow[0]) { selectObj.px = iMouseX - selectObj.x; selectObj.py = iMouseY - selectObj.y; } if (selectObj.bHow[1]) { selectObj.px = iMouseX - selectObj.x - selectObj.w; selectObj.py = iMouseY - selectObj.y; } if (selectObj.bHow[2]) { selectObj.px = iMouseX - selectObj.x - selectObj.w; selectObj.py = iMouseY - selectObj.y - selectObj.h; } if (selectObj.bHow[3]) { selectObj.px = iMouseX - selectObj.x; selectObj.py = iMouseY - selectObj.y - selectObj.h; } if (iMouseX > selectObj.x + selectObj.csizeh && iMouseX < selectObj.x + selectObj.w - selectObj.csizeh && iMouseY > selectObj.y + selectObj.csizeh && iMouseY < selectObj.y + selectObj.h - selectObj.csizeh) { selectObj.bDragAll = true; } for (var i = 0; i < 4; i++) { if (selectObj.bHow[i]) { selectObj.bDrag[i] = true; } } }; canvas.mouseout(canvasMouseOut); canvas.mouseup(canvasMouseUp); canvas.on("touchend", canvasMouseUp); this.getImageData = function (previewID) { var tmpCanvas = $("<canvas></canvas>")[0]; var tmpCtx = tmpCanvas.getContext("2d"); if (tmpCanvas && selectObj) { tmpCanvas.width = selectObj.w; tmpCanvas.height = selectObj.h; tmpCtx.drawImage(image, selectObj.x, selectObj.y, selectObj.w, selectObj.h, 0, 0, selectObj.w, selectObj.h); if (document.getElementById(previewID)) { document.getElementById(previewID).src = tmpCanvas.toDataURL(); document.getElementById(previewID).style.border = "1px solid #ccc"; } return tmpCanvas.toDataURL(); } }; } function autoResizeImage(maxWidth, maxHeight, objImg) { var img = new Image(); img.src = objImg.src; var hRatio; var wRatio; var ratio = 1; var w = objImg.width; var h = objImg.height; wRatio = maxWidth / w; hRatio = maxHeight / h; if (w < maxWidth && h < maxHeight) { return; } if (maxWidth == 0 && maxHeight == 0) { ratio = 1; } else if (maxWidth == 0) { if (hRatio < 1) { ratio = hRatio; } } else if (maxHeight == 0) { if (wRatio < 1) { ratio = wRatio; } } else if (wRatio < 1 || hRatio < 1) { ratio = (wRatio <= hRatio ? wRatio : hRatio); } else { ratio = (wRatio <= hRatio ? wRatio : hRatio) - Math.floor(wRatio <= hRatio ? wRatio : hRatio); } if (ratio < 1) { if (ratio < 0.5 && w < maxWidth && h < maxHeight) { ratio = 1 - ratio; } w = w * ratio; h = h * ratio; } objImg.height = h; objImg.width = w; }
The above is the entire content of this article. I hope it will be helpful to everyone’s learning. More related Please pay attention to the PHP Chinese website for content!
Related recommendations:
HTML5 Canvas progressive filling and transparency to achieve image Mask effect
How to use canvas to achieve image mosaic
The above is the detailed content of Use JavaScript and canvas to crop images. For more information, please follow other related articles on the PHP Chinese website!

H5 and HTML5 refer to the same thing, namely HTML5. HTML5 is the fifth version of HTML, bringing new features such as semantic tags, multimedia support, canvas and graphics, offline storage and local storage, improving the expressiveness and interactivity of web pages.

H5referstoHTML5,apivotaltechnologyinwebdevelopment.1)HTML5introducesnewelementsandAPIsforrich,dynamicwebapplications.2)Itsupportsmultimediawithoutplugins,enhancinguserexperienceacrossdevices.3)SemanticelementsimprovecontentstructureandSEO.4)H5'srespo

The tools and frameworks that need to be mastered in H5 development include Vue.js, React and Webpack. 1.Vue.js is suitable for building user interfaces and supports component development. 2.React optimizes page rendering through virtual DOM, suitable for complex applications. 3.Webpack is used for module packaging and optimize resource loading.

HTML5hassignificantlytransformedwebdevelopmentbyintroducingsemanticelements,enhancingmultimediasupport,andimprovingperformance.1)ItmadewebsitesmoreaccessibleandSEO-friendlywithsemanticelementslike,,and.2)HTML5introducednativeandtags,eliminatingthenee

H5 improves web page accessibility and SEO effects through semantic elements and ARIA attributes. 1. Use, etc. to organize the content structure and improve SEO. 2. ARIA attributes such as aria-label enhance accessibility, and assistive technology users can use web pages smoothly.

"h5" and "HTML5" are the same in most cases, but they may have different meanings in certain specific scenarios. 1. "HTML5" is a W3C-defined standard that contains new tags and APIs. 2. "h5" is usually the abbreviation of HTML5, but in mobile development, it may refer to a framework based on HTML5. Understanding these differences helps to use these terms accurately in your project.

H5, or HTML5, is the fifth version of HTML. It provides developers with a stronger tool set, making it easier to create complex web applications. The core functions of H5 include: 1) elements that allow drawing graphics and animations on web pages; 2) semantic tags such as, etc. to make the web page structure clear and conducive to SEO optimization; 3) new APIs such as GeolocationAPI support location-based services; 4) Cross-browser compatibility needs to be ensured through compatibility testing and Polyfill library.

How to create an H5 link? Determine the link target: Get the URL of the H5 page or application. Create HTML anchors: Use the <a> tag to create an anchor and specify the link target URL. Set link properties (optional): Set target, title, and onclick properties as needed. Add to webpage: Add HTML anchor code to the webpage where you want the link to appear.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version
Visual web development tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.