画布 - 裁剪不同形状的图像 [英] canvas- Cropping images in different shapes

查看:128
本文介绍了画布 - 裁剪不同形状的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个网站上工作,我需要裁剪不同形状的图片。
我发现很多库,我测试了一些,但主要的问题是,他们只能裁剪图像预定义的形状,如矩形,圆。我需要的是剪裁任何形状的图像



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



我可以使用php,jquery和其他平台



您能帮我处理这个问题吗?



King Regards

解决方案

这里有一种使用html5 Canvas的方法:





1。使用area元素的 coords 在画布上绘制路径。

  //假定你把coords点作为{x:,y:}对象放到一个points []数组中:

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。在画布上绘制图像。图片将剪切到您定义的路径中:

  ctx.drawImage(yourImageObject,0,0); 

4。创建第二个大小为裁剪路径大小的画布,并使用 context.drawImage 的裁剪版本将裁剪后的图片仅绘制到第二个画布上。

  //详情请参阅下面的演示

5。从第二个画布创建新的图片()...任务完成!

  //创建新图片()从第二个画布

var clippedImage = new Image();
clippedImage.onload = function(){
//将新图像附加到页面
document.body.appendChild(clippedImage);
}
clippedImage.src = secondCanvas.toDataURL();

注释示例代码和演示:



< =snippet-code-js lang-js prettyprint-override> // canvas相关变量varar 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; //设置一些canvas stylectx.strokeStyle = black'; //一个数组,用于保存定义剪切区域的用户的点击点pointvar points = []; //加载图像var img = new Image(); img.crossOrigin ='anonymous'; img.onload = start; img.src =https://dl.dropboxusercontent.com/u/139992952/multple/houses1.jpg; function start(){//调整画布以适合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){//告诉浏览器我们正在处理这个事件e.preventDefault (); e.stopPropagation(); // calculate mouseX& mouse y mx = parseInt(e.clientX-offsetX); my = parseInt(e.clientY-offsetY); // push the clicked point to the points [] array points.push({x:mx,y:my}); //显示用户当前剪切路径outlineIt()的轮廓; //如果用户点击回原来的圆形//然后完成剪辑if(points.length> 1){var dx = mx-points [0] .x; var dy = my -points [0] .y; if(dx * dx + dy * dy <10 * 10){clipIt(); }}} //在指定的opacity函数重绘图像drawImage(alpha){ctx.clearRect(0,0,cw,ch); ctx.globalAlpha = alpha; ctx.drawImage(img,0,0); ctx.globalAlpha = 1.00;} //显示当前潜在削减路径函数outlineIt(){drawImage(0.25); ctx.beginPath(); ctx.moveTo(points [0] .x,point [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();} //将所选路径剪切到新的canvas函数clipIt(){//计算用户裁剪区域的大小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> maxX){maxX = px;} if(p.y> maxY)if(p.x

  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>点击以勾勒出剪裁区域。< br> ;< / h4>< button id = reset>重设剪辑路径< / button>< br>< canvas id =canvaswidth = 400 height = 300& ; / canvas>< p>用户剪切的图片< / p>  


I'm working on a website that I need to crop images on different shapes . I found lots of libraries and I've tested some ,but the main problem is they only can crop images on pre defined shapes like rectangle , circle . What I need is to crop images in any shapes

for example ,I've written a code the users can define their shapes ( by using Map Area ) and the exact shape is make ,Now I need to crop image or copy this area and make a new image from it .

I can use php ,jquery and other platforms

Could you help me to manage this problem ?

King Regards

解决方案

Here's one way to do it using html5 Canvas:

1. Use the area element's coords to draw a path on the 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. Create a clipping path from the coords path you've just defined:

    ctx.clip();

3. Draw the image on the canvas. The image will be clipped into your defined path:

     ctx.drawImage(yourImageObject,0,0);

4. Create a second canvas sized to the clipping path size and use the clipping version of context.drawImage to draw just the clipped image onto the second canvas.

// see demo below for details 

5. Create a new Image() from the second canvas...Mission Accomplished!

// 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();

Annotated example code and a Demo:

// 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>

这篇关于画布 - 裁剪不同形状的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆