2013-03-22 170 views
5

我只是想在曲線中剪輯圖像..但沒有發生這種情況.. 只有圖像顯示,但沒有與剪輯。帆布夾圖像在一個圓圈

HTML

<canvas id="leaf" width="500" height="500" style='left: 0; 
position: absolute; top: 0;'></canvas> 

的JavaScript

var canvas = document.getElementById('leaf'); 
var context = canvas.getContext('2d'); 

/* 
* save() allows us to save the canvas context before 
* defining the clipping region so that we can return 
* to the default state later on 
*/ 

context.save(); 
context.beginPath(); 
context.moveTo(188, 150); 
context.quadraticCurveTo(288, 0, 388, 150); 
context.lineWidth = 10; 
context.quadraticCurveTo(288, 288, 188, 150); 
context.lineWidth = 10; 

context.clip(); 

context.beginPath(); 
var imageObj = new Image(); 
imageObj.onload = function() 
{ 
context.drawImage(imageObj, 10, 50); 
}; 

imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg'; 

/* context.beginPath(); 
context.arc(x - offset, y - offset, radius, 0, 2 * Math.PI, false); 
context.fillStyle = 'yello'; 
context.fill(); 
*/ 

/* 
* restore() restores the canvas context to its original state 
* before we defined the clipping region 
*/ 

context.restore(); 
context.beginPath(); 
context.moveTo(188, 150); 
context.quadraticCurveTo(288, 0, 388, 150); 
context.lineWidth = 10; 
context.quadraticCurveTo(288, 288, 188, 150); 
context.lineWidth = 10; 

context.strokeStyle = 'blue'; 
context.stroke(); 

回答

5

你必須一切從線context.save();移動到context.clip();的函數對象裏面你imgObjonload處理程序:

imageObj.onload = function() 
{ 
    context.save(); 
    context.beginPath(); 
    context.moveTo(188, 150); 
    context.quadraticCurveTo(288, 0, 388, 150); 
    context.lineWidth = 10; 
    context.quadraticCurveTo(288, 288, 188, 150); 
    context.lineWidth = 10; 
    context.clip(); 
    context.drawImage(imageObj, 10, 50); 
}; 

查看http://jsfiddle.net/CSkP6/1/舉例。

1

當你的腳本啓動幾次後,你的圖像被加載,你沒有更多的剪輯畫布,因爲你以後還原它。
您需要執行一個繪圖函數,並在您的onload函數中調用它:

function drawClipped(context, myImage) = { 
    context.save(); 
    context.beginPath(); 
    context.moveTo(188, 150); 
    context.quadraticCurveTo(288, 0, 388, 150); 
    context.lineWidth = 10; 
    context.quadraticCurveTo(288, 288, 188, 150); 
    context.lineWidth = 10; 
    context.clip(); 
    context.drawImage(myImage, 10, 50); 
    context.restore(); 
}; 

var imageObj = new Image(); 
imageObj.onload = function() { 
    drawClipped(context, imageObj); 
}; 

imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg';