• 【前端】图片裁剪路径绘制及图片不规则裁剪


    说明

     项目中可能需要用户根据展示的图片,然后绘制需要裁剪的路径,再根据绘制的坐标进行裁剪,以下是前端的裁剪路径绘制的代码示例,后端可以根据当前的获取到的坐标进行裁剪,裁剪的坐标保存在coordinate数组中。

    代码 

    1. html>
    2. <html>
    3. <body>
    4. <canvas id="myCanvas" style="border:1px solid #d3d3d3;">
    5. Your browser does not support the HTML5 canvas tag.
    6. canvas>
    7. <script>
    8. var canvas = document.getElementById("myCanvas");
    9. var ctx = canvas.getContext("2d");
    10. var img = new Image();
    11. img.onload = function() {
    12. canvas.width = img.width;
    13. canvas.height = img.height;
    14. ctx.drawImage(img, 0, 0, img.width, img.height);
    15. }
    16. img.src = 'https://img0.baidu.com/it/u=2604378473,1820239902&fm=253&fmt=auto&app=120&f=JPEG?w=627&h=418';
    17. var x = 0;
    18. var y = 0;
    19. var coordinate = []
    20. canvas.onmousemove = function(e) {
    21. handleClearCanvas();
    22. handleMouseMove(e);
    23. handleClickShape();
    24. }
    25. // 点击获取坐标
    26. canvas.onclick = function(e) {
    27. coordinate.push({
    28. x: x,
    29. y: y
    30. })
    31. }
    32. canvas.ondblclick = function(e) {
    33. handleClearCanvas();
    34. coordinate = [];
    35. }
    36. // 清理画布
    37. function handleClearCanvas() {
    38. ctx.clearRect(0, 0, canvas.width, canvas.height);
    39. ctx.drawImage(img, 0, 0, img.width, img.height);
    40. }
    41. // 移动光标时的线
    42. function handleMouseMove(e) {
    43. x = e.clientX - canvas.offsetLeft;
    44. y = e.clientY - canvas.offsetTop;
    45. ctx.beginPath()
    46. ctx.moveTo(x, 0);
    47. ctx.lineTo(x, img.height);
    48. ctx.moveTo(0, y);
    49. ctx.lineTo(img.width, y);
    50. ctx.stroke();
    51. // 显示光标位置信息
    52. ctx.font = "15px Arial";
    53. ctx.fillStyle = "red";
    54. // 在canvas外显示光标位置
    55. ctx.fillText("(" + x + ", " + y + ")", 5, 30);
    56. }
    57. // 选择的线
    58. function handleClickShape() {
    59. if (coordinate.length === 0){
    60. return
    61. }
    62. if (coordinate.length === 1) {
    63. const item = coordinate[0]
    64. ctx.fillText("☆", item.x, item.y);
    65. return
    66. }
    67. for (let index = 1 ; index < coordinate.length; index++){
    68. const prev = coordinate[index - 1]
    69. const next = coordinate[index]
    70. ctx.beginPath();
    71. ctx.moveTo(prev.x, prev.y);
    72. ctx.lineTo(next.x, next.y);
    73. ctx.stroke();
    74. }
    75. }
    76. script>
    77. body>
    78. html>

    结果

  • 相关阅读:
    工厂方法模式 创建型模式之四
    Cookie和Session的各自作用、使用场景、java操作代码(创建、获取等操作)
    pycharm使用
    spring事务失效场景
    N字型变换
    spring cloud feign实现服务的远程调用和负载均衡
    为什么说企业内部管理需要ERP系统
    『 MySQL数据库 』数据库之表的约束
    激光条纹中心线提取算法FPGA实现方案
    vue-cli复习
  • 原文地址:https://blog.csdn.net/qq_38428623/article/details/133942184