Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/372.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/30.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript HTML5画布围绕中心旋转渐变_Javascript_Html_Canvas - Fatal编程技术网

Javascript HTML5画布围绕中心旋转渐变

Javascript HTML5画布围绕中心旋转渐变,javascript,html,canvas,Javascript,Html,Canvas,我试图围绕画布的中心点旋转渐变,但我没有运气找到正确的计算方法,为了实现这一点,需要进行正确的计算 我想做的一个例子是:。旋转滑块正是我想要做的,但我已经看过了源代码,逻辑似乎可以用cos/sin简化很多(虽然我不是这方面的专家,所以我要问这个问题) 我发现这条线()有点帮助,但它围绕中心点旋转,而不是像第一个例子中的旋转滑块那样粘在中心点上 在此方面的任何帮助都将不胜感激 谢谢旋转渐变。 简单的旋转。 如果你不担心渐变适合画布,那么简单的旋转就能解决问题 首先,你必须计算出渐变的最大长度,这

我试图围绕画布的中心点旋转渐变,但我没有运气找到正确的计算方法,为了实现这一点,需要进行正确的计算

我想做的一个例子是:。旋转滑块正是我想要做的,但我已经看过了源代码,逻辑似乎可以用cos/sin简化很多(虽然我不是这方面的专家,所以我要问这个问题)

我发现这条线()有点帮助,但它围绕中心点旋转,而不是像第一个例子中的旋转滑块那样粘在中心点上

在此方面的任何帮助都将不胜感激

谢谢

旋转渐变。
简单的旋转。 如果你不担心渐变适合画布,那么简单的旋转就能解决问题

首先,你必须计算出渐变的最大长度,这样当它是对角线时,它仍然适合画布

const maxLength = Math.sqrt(canvas.width * canvas.width + canvas.height * canvas.height);
然后,您可以创建渐变,如下所示

var angle = ?; // The angle in radians
               // A value of 0 if a gradient from right to left
const gradient = ctx.createLinearGradient(
     // the start of the gradient added to the center
     canvas.width / 2 + Math.cos(angle) * maxLength * 0.5,
     canvas.height / 2 + Math.sin(angle) * maxLength * 0.5,
     // the end of the gradient subtracted from the center
     canvas.width / 2 - Math.cos(angle) * maxLength * 0.5,
     canvas.height / 2 - Math.sin(angle) * maxLength * 0.5
)
这可以工作,但当渐变不沿对角线时,它将剪裁渐变

拟合对角线示例
const eachOf=(a,cb)=>{var i=0;const len=a.length;while(i col&&g.addColorStop(i/(colors.length-1),col));
返回g;
}
功能更新(计时器){
ctx.fillStyle=createRotatedGradient(计时器/1000,渐变颜色);
ctx.fillRect(0,0,w,h);
requestAnimationFrame(更新);
}
requestAnimationFrame(更新)
canvas{border:2px纯黑;}

完美答案,非常感谢。你救了我很多痛苦