Javascript 画布线性渐变

Javascript 画布线性渐变,javascript,canvas,linear-gradients,Javascript,Canvas,Linear Gradients,我想在我的三次曲线上添加我的线性渐变,同时移动鼠标改变它的位置。但不知怎的,它不会起作用。如果我停止改变它的位置并在屏幕上固定它,它就会工作 document.addEventListener("DOMContentLoaded", function() { var canvas = document.querySelector("canvas"); canvas.height = window.innerHeight; canvas.width = window.innerWid

我想在我的三次曲线上添加我的线性渐变,同时移动鼠标改变它的位置。但不知怎的,它不会起作用。如果我停止改变它的位置并在屏幕上固定它,它就会工作

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 prev = {};
  var mouse = {};

  window.addEventListener("mousemove", function(e) {
    //prev.x = mouse.x;
    //prev.y = mouse.y;

    mouse.x = e.pageX;
    mouse.y = e.pageY;
  });

  function draw() {
    ctx.fillStyle = "#CCC";
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    var grad = ctx.createLinearGradient(50, 50, 150, 150);
    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((canvas.width / 2), (canvas.height / 2));

    ctx.quadraticCurveTo(((canvas.width / 2) - 100), (canvas.height / 2 + 100), (mouse.x), (mouse.y));
    ctx.stroke()
  };

  window.addEventListener("mousemove", draw);

});

当我从DOMContentLoaded事件函数中删除它时,它可以在以下JSFIDLE中正常工作:


除非你的意思是你的梯度,它不会随着曲线移动,但现在这是正常的行为。在每次绘图时创建渐变时,您也可以通过移动鼠标位置来移动渐变。

您知道为什么在删除加载的渐变时它会起作用吗?当我不添加代码时,它经常显示代码不工作。传递鼠标位置是什么意思?我必须在哪里通过它们?没有时间将您的解决方案作为本地项目进行测试,因此我使用了fiddle,我相信它将在正确的时间插入脚本,而无需加载DOMContentLoaded。(请纠正我这一点)。尝试在正文末尾的HTML内容后添加脚本标记,看看是否仍需要加载DOMContentLoaded。线性渐变需要起点和终点。这些是您为createLinearGradient方法提供的数字。如果给定的起点和终点与曲线相同,则渐变应跟随鼠标。
  var canvas = document.querySelector("canvas");
  canvas.id= 'test'
  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(){
   console.log('dra');
    ctx.fillStyle = "#CCC";
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    var grad = ctx.createLinearGradient(50, 50, 150, 150);
    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((canvas.width/2), (canvas.height/2));

    ctx.quadraticCurveTo(((canvas.width/2)-100), (canvas.height/2+100), (mouse.x), (mouse.y));
    ctx.stroke()
  }

  window.addEventListener("mousemove", draw);