简体   繁体   中英

Canvas Linear Gradient

I wanna add my linear gradient on my cubic Curve while changing its position while moving my mouse. But somehow it won't work. If i stop changing its position and fix it on my screen it works.

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);

});

When I remove it from the DOMContentLoaded event function it works fine in this jsfiddle : https://jsfiddle.net/wboq6bsk/

  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);

Unless you mean your gradient it not moving with the curve, but right now this has normal behavior. You can probably get the gradient to move too by passing in mouse positions while creating the gradient on each draw.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM