jquery 计算画布渐变的旋转

oknrviil  于 11个月前  发布在  jQuery
关注(0)|答案(1)|浏览(80)

我尝试使用渐变来填充画布的一个区域,但我希望能够设置渐变的Angular 。
我知道这是可能的,通过在创建梯度(ctx.createLinearGradient(x1, y1, x2, y2))时使用不同的值,如下所示:


的数据
但我似乎无法理解将Angular (弧度)转换为梯度大小所需的数学运算,从而产生相同的Angular (我所指的Angular 与梯度方向垂直,因此0弧度Angular 将显示右侧的梯度)
简而言之,我如何将(数量)弧度转换为X乘Y形状?

$(document).ready(function(){
    var canvas = document.getElementById("test");
    var ctx = canvas.getContext("2d");
    var angle = 0.5;
    
    ctx.beginPath();
    ctx.moveTo(100, 100);
    ctx.arc(100, 100, 100, 0, -angle, true);
    ctx.lineTo(100, 100);
    ctx.closePath();

    // Convert angle into coordinates to tilt the grad
    // grad should be perpendicular to the top edge of the arc
    var grad = ctx.createLinearGradient(0, 0, 0, 100);
    
    grad.addColorStop(0, "rgba(0,0,0,0)");
    grad.addColorStop(1, "rgba(0,0,0,0.8)");
    ctx.fillStyle = grad;
    ctx.fill();
})

个字符
(So没有人会浪费时间:我特别不想在这种情况下使用context.rotate()

jhiyze9q

jhiyze9q1#

你可以使用cos和sin的Angular 来定义给出梯度的直线。剩下的唯一事情就是给出长度:

var length = 100, angle = 0;
ctx.createLinearGradient(x, y, x + Math.cos(angle) * length, y + Math.sin(angle) * length);

字符串
渐变将沿沿着(垂直)给定的线渲染。
没有说明,但是如果你需要根据Angular 和盒子来计算线的长度,你可以使用law of sines来完成(以这种方式使用)。下面的例子使用固定的半径。你也可以通过计算length = Math.sqrt(diffX*diffX + diffY*diffY);来使用(x1,x2)的最大长度。

示例

var ctx = c.getContext("2d"),
    x1 = 150, y1 = 150, x2, y2, angle,
    length = 150;

render();
cAngle.oninput = render;

function render() {
  
  angle = +cAngle.value / 180 * Math.PI;

  // calculate gradient line based on angle
  x2 = x1 + Math.cos(angle) * length;
  y2 = y1 + Math.sin(angle) * length;
  
  // create and render gradient
  ctx.fillStyle = ctx.createLinearGradient(x1, y1, x2, y2);
  ctx.fillStyle.addColorStop(0, "#fff");
  ctx.fillStyle.addColorStop(1, "#07f");
  ctx.fillRect(0, 0, 300, 300);
  
  // show definition line
  ctx.beginPath();
  ctx.moveTo(x1, y1);
  ctx.lineTo(x2, y2);
  ctx.stroke();
}
<label>Angle: <input id=cAngle max=359 type=range value=0></label><br>
<canvas id=c height=300></canvas>

的数据

相关问题