6

我只是想以曲线剪辑图像..但没有发生这种情况..只有图像显示,但没有剪辑。

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

2 回答 2

8

您必须将所有内容从行移动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/ 。

于 2013-03-22T09:14:05.133 回答
1

当你的脚本启动几次后,你的图像被加载,你没有更多的剪辑画布,因为你之后恢复它。
你需要做一个 drawClipped 函数,并在你的 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';
于 2013-03-22T09:17:30.417 回答