2014-09-19 41 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>