2014-09-19 82 views
0

我跟随此(https://github.com/netplayer/crop)存储库,并创建图像裁剪工具进行了一些更改。当我使用图案和线条裁剪图像时,图像会以锯齿状边缘裁剪。我怎样才能去除锯齿边缘,并应用像Photoshop.Here羽毛的特征图像周围的一些影子是fiddlehtml5帆布图像作物与软边

这里是我的代码的相关部分

var canvas = document.getElementById('myCanvas'); 
    var ctx = canvas.getContext('2d'); 
    var points=[]; 
    ctx.save(); 
    ctx.beginPath(); 
    var offset = $('#myCanvas').offset(); 
    for (var i = 0; i < points.length; i += 2) { 
     var x = parseInt(jQuery.trim(points[i])); 
     var y = parseInt(jQuery.trim(points[i + 1])); 
     if (i == 0) { 
      ctx.moveTo(x - offset.left, y - offset.top); 
     } else { 
      ctx.lineTo(x - offset.left, y - offset.top); 
     } 



    } 
    ctx.restore(); 
    var pattern = ctx.createPattern(imageObj, "repeat"); 
    ctx.fillStyle = pattern; 
    ctx.fill(); 

回答

2

下面是使用合成的一种方式和shadowing:

  • 从您的路径创建一个蒙版图像。蒙版是用户填充的路径,其边缘使用阴影羽化。下面的图像是一个形状像星星的面具 - 注意用阴影创建的羽毛边缘。

enter image description here

  • 画在画布上的面具。

  • 将合成设置为'source-in',这将导致任何新绘图仅在现有像素不透明的情况下绘制。

  • 在画布上绘制您的汽车图像。由于合成,图像将只在用户的路径中绘制,并且也会像蒙版一样羽化。

enter image description here

实施例的代码和一个演示:

var canvas=document.getElementById("canvas"); 
 
var ctx=canvas.getContext("2d"); 
 

 
var fadeLength=20; 
 

 
var img=new Image(); 
 
img.onload=start; 
 
img.src="https://dl.dropboxusercontent.com/u/139992952/multple/car.jpg"; 
 
function start(){ 
 

 
    var mask=document.createElement('canvas'); 
 
    var mctx=mask.getContext('2d'); 
 

 
    canvas.width=mask.width=img.width; 
 
    canvas.height=mask.height=img.height; 
 

 
    mctx.translate(-500,0); 
 

 
    mctx.shadowColor='black'; 
 
    mctx.shadowOffsetX=500; 
 
    mctx.shadowOffsetY=0; 
 
    mctx.shadowBlur=fadeLength; 
 

 
    drawStar(mctx,150,120,5,90,30); 
 
    drawStar(mctx,150,120,5,90,30); 
 

 
    mctx.translate(500,0); 
 

 
    ctx.drawImage(mask,0,0); 
 

 
    ctx.globalCompositeOperation='source-in' 
 
    ctx.drawImage(img,0,0); 
 

 
} 
 

 

 
function drawStar(ctx,cx,cy,spikes,outerRadius,innerRadius){ 
 
    var rot=Math.PI/2*3; 
 
    var x=cx; 
 
    var y=cy; 
 
    var step=Math.PI/spikes; 
 

 
    ctx.strokeSyle="#000"; 
 
    ctx.beginPath(); 
 
    ctx.moveTo(cx,cy-outerRadius) 
 
    for(i=0;i<spikes;i++){ 
 
    x=cx+Math.cos(rot)*outerRadius; 
 
    y=cy+Math.sin(rot)*outerRadius; 
 
    ctx.lineTo(x,y) 
 
    rot+=step 
 

 
    x=cx+Math.cos(rot)*innerRadius; 
 
    y=cy+Math.sin(rot)*innerRadius; 
 
    ctx.lineTo(x,y) 
 
    rot+=step 
 
    } 
 
    ctx.lineTo(cx,cy-outerRadius) 
 
    ctx.closePath(); 
 
    ctx.fillStyle='black'; 
 
    ctx.fill(); 
 
}
body{ background-color:white; padding:10px;} 
 
canvas{border:1px solid red; background-color:black;}
<canvas id="canvas" width=300 height=300></canvas>