gpt4 book ai didi

javascript - 将 Canvas 弧线移向鼠标

转载 作者:搜寻专家 更新时间:2023-10-31 23:09:44 25 4
gpt4 key购买 nike

所以现在我有一个简单的 Canvas 元素,它具有创建随机颜色、大小和弧(圆)位置的功能。

生成这些随机圆圈的随机位置的“for”循环每 100 毫秒执行 1 个圆圈(这是在单击时完成的)。

我想知道如何让每个圆圈慢慢靠近光标,然后随着光标移动到哪里。

http://jsfiddle.net/JXXgx/

最佳答案

你可以尝试这样的事情:

var MAXIMUM_AMOUNT = 1000,
FPS = 30,
targetToGo, //
shapes = []; //storage of circles

//Helper class
function CircleModel(x,y,r,color){
this.x = x;
this.y = y;
this.r = r;
this.color = color;
}
function initScene(){
//Listening for mouse position changes
$('canvas').mousemove(function(e){
targetToGo.x = e.pageX;
targetToGo.y = e.pageY;
});
//Circle generation timer
var intervalID = setInterval(function(){
if( shapes.length < MAXIMUM_AMOUNT ){
for(var i = 0; i < 1; i++){
//Generating random parameters for circle
var randX = targetToGo.x - 500 + Math.floor(Math.random() * 1000); //position x
var randY = targetToGo.y - 300 + Math.floor(Math.random() * 600); //position y
var randRadius = Math.floor(Math.random() * 12); //radius
var randColor = "#"+("000000"+(0xFFFFFF*Math.random()).toString(16)).substr(-6); //color
//Adding circle to scene
shapes.push( new CircleModel(randX,randY,randRadius,randColor) );
}
}else{
clearInterval(intervalID);
}
}, 100);
//Starts rendering timer -
// '1000' represents 1 second,as FPS represents seconds,not miliseconds
setInterval(render,1000/FPS);
}
function render(){
var ctx = $('canvas')[0].getContext("2d");
var circle;
//Clearing the scene
ctx.clearRect(0,0,$('canvas').width(),$('canvas').height());
//Drawing circles
for(var i=0; i < shapes.length;++i){
circle = shapes[i];
//(animation part)
//repositioning circle --
// (1/circle.r) is a degree of inertion,and the bigger radius,the slower it moves
circle.x += (targetToGo.x - circle.x)*1/circle.r;
circle.y += (targetToGo.y - circle.y)*1/circle.r;
////////////////////////////////////////////
ctx.fillStyle = circle.color;
ctx.beginPath();
ctx.arc(circle.x, circle.y, circle.r, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();
}
}

$("canvas").click(function(e){
targetToGo = {x: e.pageX, y:e.pageY};
initScene();
});

将此代码放入 $(document).ready 处理程序中。

Demo

关于javascript - 将 Canvas 弧线移向鼠标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11334843/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com