Цвет RGB не обновляется при переходе от прослушивателя событий - PullRequest
2 голосов
/ 12 мая 2019

Я пытаюсь создать изменяющую цвет спиральную анимацию.Цвет спирали должен обновляться в зависимости от положения мыши и должен только обновляться при срабатывании / срабатывании событий mousemove или touchmove.Проблема в том, что когда страница загружается, пользователь перемещает мышь, цвет вычисляется, а затем присваивается значение c.strokeStyle, а затем не изменяется.Я не думаю, что это должно происходить, поскольку console.log("rgb("+Math.round(r)+","+Math.round(g)+","+Math.round(b)+")") действительно работает и показывает значение в консоли.Код выглядит следующим образом:

var canvas = document.getElementById('canvas');
var c = canvas.getContext('2d');

canvas.width = innerWidth;
canvas.height = innerHeight;

// mouse and related functions with event listeners
var mouse = {
  x: undefined,
  y: undefined
}

window.addEventListener('mousemove', function(event) {
  mouse.x = event.x;
  mouse.y = event.y;
  drawSpiral();
})

window.addEventListener('touchmove', function (event) {
  mouse.x = event.x;
  mouse.y = event.y;
  drawSpiral();
})

function generateRGB() {
  // handled as rgb
  var r = map_range(mouse.x, 0, canvas.width, 0, 255);
  var g = map_range(mouse.y, 0, canvas.height, 0, 255);;
  var b = map_range(mouse.x+mouse.y, 0, canvas.width, 0, 255);;

  // console.log("rgb("+Math.round(r)+","+Math.round(g)+","+Math.round(b)+")")
  return "rgb("+Math.round(r)+","+Math.round(g)+","+Math.round(b)+")";

}

// used to map the mouse x, y to 0, 255 for colour
function map_range(value, low1, high1, low2, high2) {
    return low2 + (high2 - low2) * (value - low1) / (high1 - low1);
}

// spiral drawing

var distance = 800;

var x = 10;
var y = 10;

function updatePosition(xChange, yChange) {
  x += xChange;
  y += yChange;
}


function drawSpiral(colour=generateRGB()) {
  c.beginPath()
  //c.fillRect(0, 0, canvas.width, canvas.height)
  c.strokeStyle = colour;

  while (distance > 0) {

    c.moveTo(x, y);

    c.lineTo(x+distance, y); // move right
    updatePosition(distance, 0);
    distance -= 6;

    c.lineTo(x, y+distance); // move down
    updatePosition(0, distance);

    c.lineTo(x-distance, y); // move left
    updatePosition(-distance, 0);
    distance -= 6;

    c.lineTo(x, y-distance); // move up
    updatePosition(0, -distance);

    c.stroke();
  }

  c.closePath();
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Square Spiral</title>
  </head>
  <body>
    <canvas id="canvas"></canvas>
    <script type="text/javascript" src="main.js"></script>
  </body>
</html>

Любая помощь будет принята с благодарностью.Спасибо!:)

1 Ответ

3 голосов
/ 12 мая 2019

Проблема заключалась в том, что после первого рисования спирали начальные переменные x, y и distance принимают новые значения, которые не позволяют снова нарисовать спираль при последующих вызовах.

Они должны быть сброшены к своим начальным значениям каждый раз в drawSpiral ():

  // re-initialize the starting variables each time drawSpiral is run
  distance = 800;
  x= 10;
  y= 10;

См. Ниже для реализации:

var canvas = document.getElementById('canvas');
var c = canvas.getContext('2d');

canvas.width = innerWidth;
canvas.height = innerHeight;

// mouse and related functions with event listeners
var mouse = {
  x: undefined,
  y: undefined
}

window.addEventListener('mousemove', function(event) {
  mouse.x = event.x;
  mouse.y = event.y;
  drawSpiral();
})

window.addEventListener('touchmove', function (event) {
  mouse.x = event.x;
  mouse.y = event.y;
  drawSpiral();
})

function generateRGB() {
  // handled as rgb
  var r = map_range(mouse.x, 0, canvas.width, 0, 255);
  var g = map_range(mouse.y, 0, canvas.height, 0, 255);;
  var b = map_range(mouse.x+mouse.y, 0, canvas.width, 0, 255);;

 // console.log("rgb("+Math.round(r)+","+Math.round(g)+","+Math.round(b)+")")
  return "rgb("+Math.round(r)+","+Math.round(g)+","+Math.round(b)+")";

}

// used to map the mouse x, y to 0, 255 for colour
function map_range(value, low1, high1, low2, high2) {
    return low2 + (high2 - low2) * (value - low1) / (high1 - low1);
}

// spiral drawing

var distance = 800;

var x = 10;
var y = 10;

function updatePosition(xChange, yChange) {
  x += xChange;
  y += yChange;
}


function drawSpiral(colour=generateRGB()) {
  c.beginPath()
  //c.fillRect(0, 0, canvas.width, canvas.height)
  c.strokeStyle = colour;

  //*****************************************
  // reset the starting values
  //*****************************************
  distance = 800;
  x= 10;
  y= 10;
  //*****************************************
  
  while (distance > 0) {

    c.moveTo(x, y);

    c.lineTo(x+distance, y); // move right
    updatePosition(distance, 0);
    distance -= 6;

    c.lineTo(x, y+distance); // move down
    updatePosition(0, distance);

    c.lineTo(x-distance, y); // move left
    updatePosition(-distance, 0);
    distance -= 6;

    c.lineTo(x, y-distance); // move up
    updatePosition(0, -distance);

    c.stroke();
  }
  
  c.closePath();
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Square Spiral</title>
  </head>
  <body>
    <canvas id="canvas"></canvas>
    <script type="text/javascript" src="main.js"></script>
  </body>
</html>
...