javascript - canvas-裁剪不同形状的图像

标签 javascript jquery html image canvas

我在一个网站上工作,我需要裁剪不同形状的图像。 我找到了很多库并且我测试了一些,但主要问题是它们只能在预定义的形状上裁剪图像,如 rectangle , circle 。我需要的是将图像裁剪成任意形状

例如,我写了一个代码,用户可以定义他们的形状(通过使用 map 区域)并且精确的形状是 make ,现在我需要裁剪图像或复制这个区域并从中制作一个新图像。

我会用php,jquery等平台

你能帮我解决这个问题吗?

国王问候

最佳答案

这是使用 html5 Canvas 的一种方法:

enter image description here enter image description here

<强>1。使用区域元素的坐标在 Canvas 上绘制路径。

// assume you've put the `coords` points as {x:,y:} objects into a points[] array:

    ctx.beginPath();
    ctx.moveTo(points[0].x,points[0].y);
    for(var i=1;i<points.length;i++){
        var p=points[i];
        ctx.lineTo(points[i].x,points[i].y);
    }
    ctx.closePath();

<强>2。根据您刚刚定义的 coords 路径创建剪切路径:

    ctx.clip();

<强>3。在 Canvas 上绘制图像。图像将被剪切到您定义的路径中:

     ctx.drawImage(yourImageObject,0,0);

<强>4。创建大小与剪切路径大小相匹配的第二个 Canvas ,并使用 context.drawImage 的剪切版本仅将剪切后的图像绘制到第二个 Canvas 上。

// see demo below for details 

<强>5。从第二个 Canvas 创建一个新的 Image()...任务完成!

// create a new Image() from the second canvas

    var clippedImage=new Image();
    clippedImage.onload=function(){
        // append the new image to the page
        document.body.appendChild(clippedImage);
    }
    clippedImage.src=secondCanvas.toDataURL();

带注释的示例代码和演示:

// canvas related variables
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw,ch;
var $canvas=$("#canvas");
var canvasOffset=$canvas.offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;

// set some canvas styles
ctx.strokeStyle='black';

// an array to hold user's click-points that define the clipping area
var points=[];

// load the image 
var img=new Image();
img.crossOrigin='anonymous';
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/multple/houses1.jpg";
function start(){

  // resize canvas to fit the img
  cw=canvas.width=img.width;
  ch=canvas.height=img.height;

  // draw the image at 25% opacity
  drawImage(0.25);

  // listen for mousedown and button clicks
  $('#canvas').mousedown(function(e){handleMouseDown(e);});
  $('#reset').click(function(){ points.length=0; drawImage(0.25); });
}



function handleMouseDown(e){

  // tell the browser that we're handling this event
  e.preventDefault();
  e.stopPropagation();

  // calculate mouseX & mouseY
  mx=parseInt(e.clientX-offsetX);
  my=parseInt(e.clientY-offsetY);

  // push the clicked point to the points[] array
  points.push({x:mx,y:my});

  // show the user an outline of their current clipping path
  outlineIt();

  // if the user clicked back in the original circle
  // then complete the clip
  if(points.length>1){
    var dx=mx-points[0].x;
    var dy=my-points[0].y;
    if(dx*dx+dy*dy<10*10){
      clipIt();
    }
  }
}


// redraw the image at the specified opacity
function drawImage(alpha){
  ctx.clearRect(0,0,cw,ch);
  ctx.globalAlpha=alpha;
  ctx.drawImage(img,0,0);
  ctx.globalAlpha=1.00;
}

// show the current potential clipping path
function outlineIt(){
  drawImage(0.25);
  ctx.beginPath();
  ctx.moveTo(points[0].x,points[0].y);
  for(var i=0;i<points.length;i++){
    ctx.lineTo(points[i].x,points[i].y);
  }
  ctx.closePath();
  ctx.stroke();
  ctx.beginPath();
  ctx.arc(points[0].x,points[0].y,10,0,Math.PI*2);
  ctx.closePath();
  ctx.stroke();
}

// clip the selected path to a new canvas
function clipIt(){

  // calculate the size of the user's clipping area
  var minX=10000;
  var minY=10000;
  var maxX=-10000;
  var maxY=-10000;
  for(var i=1;i<points.length;i++){
    var p=points[i];
    if(p.x<minX){minX=p.x;}
    if(p.y<minY){minY=p.y;}
    if(p.x>maxX){maxX=p.x;}
    if(p.y>maxY){maxY=p.y;}
  }
  var width=maxX-minX;
  var height=maxY-minY;

  // clip the image into the user's clipping area
  ctx.save();
  ctx.clearRect(0,0,cw,ch);
  ctx.beginPath();
  ctx.moveTo(points[0].x,points[0].y);
  for(var i=1;i<points.length;i++){
    var p=points[i];
    ctx.lineTo(points[i].x,points[i].y);
  }
  ctx.closePath();
  ctx.clip();
  ctx.drawImage(img,0,0);
  ctx.restore();

  // create a new canvas 
  var c=document.createElement('canvas');
  var cx=c.getContext('2d');

  // resize the new canvas to the size of the clipping area
  c.width=width;
  c.height=height;

  // draw the clipped image from the main canvas to the new canvas
  cx.drawImage(canvas, minX,minY,width,height, 0,0,width,height);

  // create a new Image() from the new canvas
  var clippedImage=new Image();
  clippedImage.onload=function(){
    // append the new image to the page
    document.body.appendChild(clippedImage);
  }
  clippedImage.src=c.toDataURL();


  // clear the previous points 
  points.length=0;

  // redraw the image on the main canvas for further clipping
  drawImage(0.25);
}
body{ background-color: ivory; }
canvas{border:1px solid red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h4>Click to outline clipping region.<br>Click back in starting circle to complete the clip.</h4>
<button id=reset>Reset clipping path</button><br>
<canvas id="canvas" width=400 height=300></canvas>
<p>Clipped images by user</p>

关于javascript - canvas-裁剪不同形状的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27213413/

相关文章:

javascript - Jquery 验证(在表中设置错误样式)

javascript - JQuery 数据表分页

javascript - 简化糟糕的 jQuery

javascript - 关于 jQuery html()、attr() 和 val()

php - 分页显示问题php

javascript - 发布和订阅同一主题的 mqtt 最佳实践

javascript - jquery 与 JavaScript

javascript - x 分钟后关闭弹出窗口,除非有事件

javascript - textarea 直接连接到 DOM 的安全隐患

javascript - 带你的href视频