如何使用jQuery HTML Canvas图像添加裁剪功能,用户可以在其中选择某些部分

时间:2018-11-20 05:57:38

标签: javascript html canvas

我在html画布上有图像,我想使用jquery和html canvas添加裁剪功能。我已经为图像添加了渐变效果,但剩下的只是添加裁剪功能。我的概念是用户可以选择图像的某些部分通过鼠标,他可以在画布图像上绘制一个矩形(裁剪框),然后单击“裁剪”按钮,然后只能将裁剪后的图像保存在本地磁盘上

html

    <canvas id="canvas" style="height:500;width:600;"></canvas>
    <input type="color" id="color" name="color"
    value="#f6b73c">
    <button id="cropImage">Crop</button>

javascript

var mouse = {
        down: false,
        x1: null,
        y1: null,
        x2: null,
        y1: null
      };
      var grad = 'transparent';
      var ctx = canvas.getContext('2d');
      var img = new Image();
      img.onload = init;
      img.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/a/a1/D%C3%BClmen%2C_Kirchspiel%2C_B%C3%B6rnste%2C_Feld_--_2017_--_3171.jpg/500px-D%C3%BClmen%2C_Kirchspiel%2C_B%C3%B6rnste%2C_Feld_--_2017_--_3171.jpg";
      function updateGrad() {
        var cx = mouse.x1;
        var cy = mouse.y1;
        var dist = Math.hypot(mouse.x1-mouse.x2, mouse.y1-mouse.y2);          
        grad = ctx.createRadialGradient(cx, cy, 0, cx, cy, dist);        
        grad.addColorStop(1, color);
        grad.addColorStop(0, 'transparent');
      }
      function draw() {
        // draw the image
        ctx.drawImage(img, 0,0);
        // draw the gradient
        ctx.fillStyle = grad;
        ctx.fillRect(0,0,canvas.width,canvas.height);
        // draw the line?
        ctx.beginPath();
        ctx.rect(mouse.x1 - 4, mouse.y1 - 4, 8, 8);
        ctx.moveTo(mouse.x1, mouse.y1);
        ctx.lineTo(mouse.x2, mouse.y2);
        ctx.rect(mouse.x2 - 4, mouse.y2 - 4, 8, 8);
        ctx.stroke();

      } 

      function init() {
        canvas.width = this.width;
        canvas.height = this.height;
        canvas.onmousedown = mousedown;
        document.onmousemove = mousemove;
        document.onmouseup = mouseup;
        ctx.strokeStyle = 'white';
        draw();
      }      
      function mousedown(evt) {
        var rect = canvas.getBoundingClientRect();
        mouse.down = true;
        mouse.x1 = evt.clientX - rect.left;
        mouse.y1 = evt.clientY - rect.top;
      }      
      function mousemove(evt) {
        if(!mouse.down) return;
        var rect = canvas.getBoundingClientRect();
        mouse.x2 = evt.clientX - rect.left;
        mouse.y2 = evt.clientY - rect.top;
        updateGrad();
        draw();
      }      
      function mouseup(evt) {
        mouse.down = false;
      }

0 个答案:

没有答案