Холст линейный градиент - PullRequest
0 голосов
/ 17 мая 2018

Я хочу добавить мой линейный градиент на мою кубическую кривую, меняя ее положение, двигая мышь.Но как-то не получится.Если я перестану менять его положение и зафиксирую его на моем экране, это сработает.

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

});

1 Ответ

0 голосов
/ 17 мая 2018

Когда я удаляю его из функции события DOMContentLoaded, он прекрасно работает в этом 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);

Если вы не имеете в виду свой градиент, он не движется с кривой, но сейчас это имеет нормальное поведение. Вероятно, вы также можете заставить градиент двигаться, передавая позиции мыши при создании градиента на каждом рисунке.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...