画布剪辑图像在一个圆圈

时间:2013-03-22 08:55:47

标签: javascript html5 canvas

我只是想将图像剪切成曲线..但不会发生这种情况.. 只显示图像,但不显示剪辑。

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

2 个答案:

答案 0 :(得分:7)

您必须在context.save();的{​​{1}}处理程序的函数对象中将所有内容从context.clip();行移动到imgObj

onload

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

答案 1 :(得分: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';