gpt4 book ai didi

javascript - 具有两条二次曲线的 Canvas 剪辑图像

转载 作者:太空狗 更新时间:2023-10-29 14:56:05 24 4
gpt4 key购买 nike

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

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();
<canvas id="leaf" width="500" height="500" style='left: 0; 
position: absolute; top: 0;'></canvas>

最佳答案

您必须从 context.save(); 行移动所有内容至 context.clip();在你的 imgObj 的函数对象中的 onload处理程序:

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/举个例子。

关于javascript - 具有两条二次曲线的 Canvas 剪辑图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15566253/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com