我正在尝试创建一个变色螺旋动画。螺旋的颜色应根据鼠标的位置进行更新,并且仅在触发{/ {1}}或samples = malloc(nsamples * sizeof *samples);
事件时才 进行更新。问题在于,当页面加载时,用户移动鼠标,将计算出一种颜色,然后将其分配给mousemove
,然后该颜色将保持不变。我认为这不应该发生,因为touchmove
实际上可以正常工作并在控制台中显示该值。代码如下:
c.strokeStyle
console.log("rgb("+Math.round(r)+","+Math.round(g)+","+Math.round(b)+")")
任何帮助将不胜感激。谢谢! :)
答案 0 :(得分:3)
问题在于,第一次绘制螺旋线后,起始变量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>