资讯专栏INFORMATION COLUMN

Canvas裁剪图片(截选框可拖拽)

MAX_zuo / 2180人阅读

摘要:利用实现图片裁剪效果图实现思路打开图片并将图片绘制到中利用的函数来裁剪图片将转化为即可。巨坑转化为图片确认截图确认截图参考文章我是,年轻的前端攻城狮一枚,爱专研,爱技术,爱分享。文章有任何问题欢迎大家指出,也欢迎大家一起交流前端各种问题

利用Canvas实现图片裁剪 效果图

实现思路

打开图片并将图片绘制到canvas中;

利用canvas的drawImage()函数来裁剪图片;

将canvas转化为Image即可。

HTML代码:

</>复制代码

CSS代码

CSS代码基本通过javaScript添加

</>复制代码

重点JavaScript代码 变量定义、添加各事件按钮、容器等:

</>复制代码

  1. let originWidth; // 图片原始宽度
  2. let originHeight; // 图片原始高度
  3. let container = document.getElementById("container");
  4. let imgDiv = document.getElementById("imgDiv"); // 存放mycanvas
  5. let btnDiv = document.getElementById("btnDiv");
  6. let clipImgDiv = document.getElementById("clipImgDiv"); // 显示裁剪所获的图片
  7. let btn1 = document.getElementById("btn1"); // 截图按钮
  8. let btn2 = document.getElementById("btn2"); // 确认截图按钮
  9. let btn3 = document.getElementById("btn3"); // 打开文件按钮
  10. var oRelDiv = document.createElement("div"); // 截图框
  11. var scaleX = 1;// 图片宽度缩放比例(当前实际/原始)
  12. var scaleY = 1; // 图片高度缩放比例(当前实际/原始)
  13. //拖拽与拉伸方法
  14. //拖拽拉伸所需参数
  15. let params = {
  16. left: 0,
  17. top: 0,
  18. width: 0,
  19. height: 0,
  20. currentX: 0,
  21. currentY: 0,
  22. flag: false,
  23. kind: "drag"
  24. };
  25. // CSS样式修改
  26. container.style.display = "flex";
  27. container.style.flexDirection = "column";
  28. btnDiv.style.marginBottom = "20px";
  29. btnDiv.style.height = "30px";
  30. imgDiv.style.marginBottom = "20px";
  31. // 创建canvas,用于显示被裁剪图片
  32. var myCanvas = document.createElement("canvas");
  33. myCanvas.setAttribute("id", "myCanvas");
  34. myCanvas.style.display = "block";
  35. /*myCanvas.style.position = "absolute";*/
  36. myCanvas.width = 600;
  37. myCanvas.height = 600;
  38. myCanvas.style.border = "1px solid #d3d3d3";
  39. myCanvas.innerText = "您的浏览器不支持 HTML5 canvas 标签。";
  40. myCanvas.style.zIndex = "auto";
  41. var ctx = myCanvas.getContext("2d");
  42. // 被裁剪图片
  43. var img = new Image();
  44. img.src = "./images/IMG_1550.jpg";
  45. img.setAttribute("id", "img");
  46. img.width = 600;
  47. img.height = 600;
  48. img.onload = function () {
  49. console.log("onload()执行...");
  50. ctx.drawImage(img, 0, 0, 600, 600);
  51. originWidth = img.naturalWidth;
  52. originHeight = img.naturalHeight;
  53. console.log("图片原始宽度=", originWidth);
  54. console.log("图片原始高度=", originHeight);
  55. };
  56. // 裁剪得到的图片
  57. let clipImg = new Image();
  58. clipImg.src = "";
  59. clipImg.style.height = "100px";
  60. clipImg.style.width = "100px";
  61. clipImg.alt = "裁剪获得图片...";
  62. // input用于打开文件
  63. let fileInput = document.createElement("input");
  64. fileInput.setAttribute("multiple", "multiple");
  65. fileInput.setAttribute("type", "file");
  66. fileInput.setAttribute("id", "fileInput");
  67. /*btnDiv.appendChild(fileInput);*/
  68. imgDiv.appendChild(myCanvas);
  69. /*clipImgDiv.appendChild(clipImg);*/
一些简单的功能函数

</>复制代码

  1. // 生成本地图片URL地址
  2. let getObjectURL = function (file) {
  3. let url = null;
  4. if (window.createObjectURL !== undefined) { // basic
  5. url = window.createObjectURL(file);
  6. } else if (window.webkitURL !== undefined) { // webkit or chrome
  7. url = window.webkitURL.createObjectURL(file);
  8. } else if (window.URL !== undefined) { // mozilla(firefox)
  9. url = window.URL.createObjectURL(file);
  10. }
  11. return url;
  12. };
  13. // 获取指定元素DOM
  14. const ID = function (id) {
  15. return document.getElementById(id);
  16. };
  17. //获取相关CSS属性方法
  18. let getCss = function (o, key) {
  19. return o.currentStyle ? o.currentStyle[key] : document.defaultView.getComputedStyle(o, false)[key];
  20. };
打开本地图片

可伸缩截图框实现思路:

</>复制代码

  1. 截图框由8各控制截图框大小、位置小div组成,鼠标在选中截图框后在拖动鼠标的过程中会根据鼠标位置对截图框进行实时绘制

</>复制代码

  1. // 打开本地图片
  2. fileInput.addEventListener("change", function () {
  3. console.log("change()执行...");
  4. img.src = getObjectURL(this.files[0]);
  5. });
  6. btn3.addEventListener("click", function () {
  7. fileInput.click();
  8. });

截图选框的绘制、拖动、大小调整

</>复制代码

  1. btn1.addEventListener("click", function () {
  2. var clickFlag = false;
  3. // 获取canvas中图片实际大小
  4. var iCurWidth = img.width;
  5. var iCurHeight = img.height;
  6. console.log("图片当前实际宽度=", iCurWidth);
  7. console.log("图片当前实际高度=", iCurHeight);
  8. // 可调整截图框
  9. oRelDiv.innerHTML = "";
  10. oRelDiv.style.position = "absolute";
  11. oRelDiv.style.width = iCurWidth + "px";
  12. oRelDiv.style.height = iCurHeight + "px";
  13. oRelDiv.style.top = myCanvas.offsetTop + "px";
  14. console.log("oRelDiv.style.top = ", oRelDiv.style.top);
  15. oRelDiv.id = "cropContainer";
  16. var iOrigWidth = originWidth;
  17. var iOrigHeight = originHeight;
  18. scaleX = iCurWidth / iOrigWidth; // 图片宽度缩放比例(当前实际/原始)
  19. scaleY = iCurHeight / iOrigHeight; // 图片高度缩放比例(当前实际/原始)
  20. console.log("图片横向(宽度)缩放比=", scaleX);
  21. console.log("图片纵向(高度)缩放比=", scaleY);
  22. // 将oRelDiv插入到myCanvas前
  23. myCanvas.parentNode.insertBefore(oRelDiv, myCanvas);
  24. //初始化坐标与剪裁高宽
  25. var cropW = 80; //截图框默认宽度
  26. var cropH = 80; //截图框默认高度
  27. /*console.log("myCanvas.offsetLeft=", myCanvas.offsetLeft);
  28. console.log("myCanvas.offsetTop=", myCanvas.offsetTop);*/
  29. var posX = myCanvas.width / 2 - cropW / 2; // 截图框左上角x坐标
  30. var posY = myCanvas.height / 2 - cropH / 2; // 截图框左上角y坐标
  31. /*console.log("posX=",posX);
  32. console.log("posY=",posY);*/
  33. oRelDiv.innerHTML = "
    " +
  34. "
    " +
  35. "
    " +
  36. "
    " +
  37. "
    " +
  38. "
    " +
  39. "
    " +
  40. "
    " +
  41. "
    " +
  42. "
    " +
  43. "" +
  44. "" +
  45. "" +
  46. "" +
  47. "";
  48. var startDrag = function (point, target, kind) {
  49. //point是拉伸点,target是被拉伸的目标,其高度及位置会发生改变
  50. //此处的target与上面拖拽的target是同一目标,故其params.left,params.top可以共用,也必须共用
  51. //初始化宽高
  52. params.width = getCss(target, "width");
  53. params.height = getCss(target, "height");
  54. //初始化坐标
  55. if (getCss(target, "left") !== "auto") {
  56. params.left = getCss(target, "left");
  57. }
  58. if (getCss(target, "top") !== "auto") {
  59. params.top = getCss(target, "top");
  60. }
  61. //target是移动对象
  62. point.onmousedown = function (event) {
  63. params.kind = kind;
  64. params.flag = true;
  65. clickFlag = true;
  66. if (!event) {
  67. event = window.event;
  68. }
  69. var e = event;
  70. params.currentX = e.clientX; //鼠标按下时坐标x轴
  71. params.currentY = e.clientY; //鼠标按下时坐标y轴
  72. /*console.log("params.currentX=", params.currentX);
  73. console.log("params.currentY=", params.currentY);*/
  74. //防止IE文字选中,有助于拖拽平滑
  75. point.onselectstart = function () {
  76. return false;
  77. };
  78. document.onmousemove = function (event) {
  79. let e = event ? event : window.event;
  80. clickFlag = false;
  81. if (params.flag) {
  82. var nowX = e.clientX; // 鼠标移动时x坐标
  83. var nowY = e.clientY; // 鼠标移动时y坐标
  84. var disX = nowX - params.currentX; // 鼠标x方向移动距离
  85. var disY = nowY - params.currentY; // 鼠标y方向移动距离
  86. if (params.kind === "n") {
  87. //上拉伸
  88. //高度增加或减小,位置上下移动
  89. target.style.top = parseInt(params.top) + disY + "px";
  90. target.style.height = parseInt(params.height) - disY + "px";
  91. } else if (params.kind === "w") { //左拉伸
  92. target.style.left = parseInt(params.left) + disX + "px";
  93. target.style.width = parseInt(params.width) - disX + "px";
  94. } else if (params.kind === "e") { //右拉伸
  95. target.style.width = parseInt(params.width) + disX + "px";
  96. } else if (params.kind === "s") { //下拉伸
  97. target.style.height = parseInt(params.height) + disY + "px";
  98. } else if (params.kind === "nw") { //左上拉伸
  99. target.style.left = parseInt(params.left) + disX + "px";
  100. target.style.width = parseInt(params.width) - disX + "px";
  101. target.style.top = parseInt(params.top) + disY + "px";
  102. target.style.height = parseInt(params.height) - disY + "px";
  103. } else if (params.kind === "ne") { //右上拉伸
  104. target.style.top = parseInt(params.top) + disY + "px";
  105. target.style.height = parseInt(params.height) - disY + "px";
  106. target.style.width = parseInt(params.width) + disX + "px";
  107. } else if (params.kind === "sw") { //左下拉伸
  108. target.style.left = parseInt(params.left) + disX + "px";
  109. target.style.width = parseInt(params.width) - disX + "px";
  110. target.style.height = parseInt(params.height) + disY + "px";
  111. } else if (params.kind === "se") { //右下拉伸
  112. target.style.width = parseInt(params.width) + disX + "px";
  113. target.style.height = parseInt(params.height) + disY + "px";
  114. } else { //移动
  115. target.style.left = parseInt(params.left) + disX + "px";
  116. target.style.top = parseInt(params.top) + disY + "px";
  117. }
  118. }
  119. document.onmouseup = function () {
  120. params.flag = false;
  121. if (getCss(target, "left") !== "auto") {
  122. params.left = getCss(target, "left");
  123. }
  124. if (getCss(target, "top") !== "auto") {
  125. params.top = getCss(target, "top");
  126. }
  127. params.width = getCss(target, "width");
  128. params.height = getCss(target, "height");
  129. /*console.log("params.width=", params.width);
  130. console.log("params.height", params.width);*/
  131. //给隐藏文本框赋值
  132. posX = parseInt(target.style.left);
  133. posY = parseInt(target.style.top);
  134. cropW = parseInt(target.style.width);
  135. cropH = parseInt(target.style.height);
  136. if (posX < 0) {
  137. posX = 0;
  138. }
  139. if (posY < 0) {
  140. posY = 0;
  141. }
  142. if ((posX + cropW) > iCurWidth) {
  143. cropW = iCurWidth - posX;
  144. }
  145. if ((posY + cropH) > iCurHeight) {
  146. cropH = iCurHeight - posY;
  147. }
  148. //赋值
  149. ID("cropPosX").value = posX;
  150. ID("cropPosY").value = posY;
  151. ID("cropImageWidth").value = parseInt(ID("zxxCropBox").style.width);
  152. ID("cropImageHeight").value = parseInt(ID("zxxCropBox").style.height);
  153. /*console.log("posX=",posX);
  154. console.log("posY=",posY);*/
  155. };
  156. }
  157. };
  158. };
  159. //绑定拖拽
  160. startDrag(ID("zxxDragBg"), ID("zxxCropBox"), "drag");
  161. //绑定拉伸
  162. startDrag(ID("dragLeftTop"), ID("zxxCropBox"), "nw");
  163. startDrag(ID("dragLeftBot"), ID("zxxCropBox"), "sw");
  164. startDrag(ID("dragRightTop"), ID("zxxCropBox"), "ne");
  165. startDrag(ID("dragRightBot"), ID("zxxCropBox"), "se");
  166. startDrag(ID("dragTopCenter"), ID("zxxCropBox"), "n");
  167. startDrag(ID("dragBotCenter"), ID("zxxCropBox"), "s");
  168. startDrag(ID("dragRightCenter"), ID("zxxCropBox"), "e");
  169. startDrag(ID("dragLeftCenter"), ID("zxxCropBox"), "w");
  170. //图片不能被选中,目的在于使拖拽顺滑
  171. ID("myCanvas").onselectstart = function () {
  172. return false;
  173. };
  174. img.onselectstart = function () {
  175. return false;
  176. };
  177. });
所获截图绘制

</>复制代码

  1. function cropImage(img, cropPosX, cropPosY, width, height) {
  2. /*var cropContainer = ID("cropContainer");
  3. cropContainer.parentNode.removeChild(cropContainer);*/
  4. /*ctx.clearRect(0, 0, myCanvas.width, myCanvas.height);*/
  5. //sx,sy 是相对于图片的坐标。巨坑
  6. var newCanvas = document.createElement("canvas");
  7. newCanvas.setAttribute("id", "newCanvas");
  8. newCanvas.width = width * scaleX;
  9. newCanvas.height = height * scaleY;
  10. newCanvas.style.border = "1px solid #d3d3d3";
  11. var newCtx = newCanvas.getContext("2d");
  12. clipImgDiv.appendChild(newCanvas);
  13. newCtx.drawImage(img, cropPosX, cropPosY, width, height, 0, 0, width * scaleX, height * scaleY);
  14. // canvas转化为图片
  15. var newImage = new Image();
  16. newImage.src = newCanvas.toDataURL("image/png");
  17. newImage.style.marginLeft = "5px";
  18. clipImgDiv.appendChild(newImage);
  19. oRelDiv.innerHTML = "";
  20. }
确认截图

</>复制代码

  1. // 确认截图
  2. btn2.addEventListener("click", function () {
  3. console.log("clipend......");
  4. var x = document.getElementById("cropPosX").value;
  5. var y = document.getElementById("cropPosY").value;
  6. var w = document.getElementById("cropImageWidth").value;
  7. var h = document.getElementById("cropImageHeight").value;
  8. console.log("cropImage(img,", x, ",", y, ",", parseInt(w), ",", parseInt(h), ")");
  9. cropImage(img, x / scaleX, y / scaleY, parseInt(w) / scaleX, parseInt(h) / scaleY);
  10. });

参考文章:https://blog.csdn.net/qq_3870...

</>复制代码

  1. 我是Cloudy,年轻的前端攻城狮一枚,爱专研,爱技术,爱分享。
    个人笔记,整理不易,感谢阅读、点赞和收藏。
    文章有任何问题欢迎大家指出,也欢迎大家一起交流前端各种问题!

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/105121.html

相关文章

  • 画布、拖放事件、音视频

    摘要:立即对当前矩形进行填充清除矩形语法解释清除某个矩形内的绘制的内容,相当于橡皮擦绘制圆形概述方法创建弧曲线用于创建圆或部分圆语法解释圆心坐标,半径大小,绘制开始的角度。 一、拖放事件 1.1 设置拖拽 给标签设置一个draggable设置为true, 标签就可以拖拽了 1.2 拖拽事件 1.2.1拖拽元素事件 (事件对象为被拖拽元素) ondragstart 拖拽前触发 ondra...

    Nosee 评论0 收藏0
  • 画布、拖放事件、音视频

    摘要:立即对当前矩形进行填充清除矩形语法解释清除某个矩形内的绘制的内容,相当于橡皮擦绘制圆形概述方法创建弧曲线用于创建圆或部分圆语法解释圆心坐标,半径大小,绘制开始的角度。 一、拖放事件 1.1 设置拖拽 给标签设置一个draggable设置为true, 标签就可以拖拽了 1.2 拖拽事件 1.2.1拖拽元素事件 (事件对象为被拖拽元素) ondragstart 拖拽前触发 ondra...

    dailybird 评论0 收藏0
  • 画布、拖放事件、音视频

    摘要:立即对当前矩形进行填充清除矩形语法解释清除某个矩形内的绘制的内容,相当于橡皮擦绘制圆形概述方法创建弧曲线用于创建圆或部分圆语法解释圆心坐标,半径大小,绘制开始的角度。 一、拖放事件 1.1 设置拖拽 给标签设置一个draggable设置为true, 标签就可以拖拽了 1.2 拖拽事件 1.2.1拖拽元素事件 (事件对象为被拖拽元素) ondragstart 拖拽前触发 ondra...

    atinosun 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<