画布剪辑图像在一个圆圈

Puz*_*Boy 6 javascript html5 canvas

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

HTML

<canvas id="leaf" width="500" height="500" style='left: 0; 
position: absolute; top: 0;'></canvas>
Run Code Online (Sandbox Code Playgroud)

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();
Run Code Online (Sandbox Code Playgroud)

hal*_*lex 7

你必须将所有东西从行移动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);
};
Run Code Online (Sandbox Code Playgroud)

有关示例,请参见http://jsfiddle.net/CSkP6/1/.