You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

鼠标移动时Canvas二次贝塞尔曲线添加线性渐变失效问题

解决鼠标移动时二次贝塞尔曲线渐变失效的问题

我懂你的困扰——当鼠标拖动改变二次贝塞尔曲线的终点时,线性渐变效果就没了,但固定曲线位置时渐变显示完全正常。这问题出在你创建的渐变是固定在画布上的一小块区域(从(50,50)到(150,150)),一旦曲线的终点(鼠标位置)移出这个区域,曲线就不在渐变的覆盖范围内了,自然看不到渐变效果。

要修复这个问题,你需要让渐变的起点和终点跟着曲线的路径动态调整,比如把渐变的起点设为曲线的起始点,终点设为鼠标的位置,这样渐变会沿着曲线的方向延伸,不管鼠标移到哪里,曲线都能被渐变完整覆盖。

下面是修改后的可用代码:

document.addEventListener("DOMContentLoaded", function() {
  var canvas = document.querySelector("canvas");
  canvas.height = window.innerHeight;
  canvas.width = window.innerWidth;
  ctx = canvas.getContext("2d");
  ctx.fillStyle = "#CCC";
  ctx.fillRect(0, 0, canvas.width, canvas.height);
  
  var mouse = {};
  window.addEventListener("mousemove", function(e) {
    mouse.x = e.pageX;
    mouse.y = e.pageY;
  });

  function draw() {
    ctx.fillStyle = "#CCC";
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    
    // 动态绑定渐变的起点与终点:曲线起始点 → 鼠标当前位置
    const curveStartX = canvas.width / 2;
    const curveStartY = canvas.height / 2;
    var grad = ctx.createLinearGradient(curveStartX, curveStartY, mouse.x, mouse.y);
    grad.addColorStop(0, "yellow");
    grad.addColorStop(0.5, "white");
    grad.addColorStop(1, "orange");
    
    ctx.lineWidth = 10;
    ctx.lineJoin = "round";
    ctx.strokeStyle = grad;
    
    ctx.beginPath();
    ctx.moveTo(curveStartX, curveStartY);
    ctx.quadraticCurveTo(curveStartX - 100, curveStartY + 100, mouse.x, mouse.y);
    ctx.stroke();
  };

  window.addEventListener("mousemove", draw);
});

核心修改说明:

  • 将渐变的起点从固定的(50,50)替换为曲线的起始点(canvas.width/2, canvas.height/2),终点直接绑定到鼠标的实时位置(mouse.x, mouse.y)
  • 把曲线起始点的坐标提取为变量,既方便重复调用,也让代码逻辑更清晰

修改后不管鼠标移动到画布的哪个角落,渐变都会沿着曲线的方向从起点到终点自然过渡,渐变效果就能一直正常显示了。

内容的提问来源于stack exchange,提问作者user8472012

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:18:05