繁体   English   中英

如何使形状移动到鼠标位置并消失?

[英]How to make shapes move to mouse position and disappear?

柱塞:

https://plnkr.co/edit/7XslB1DDwLsAV6YAurFO?p=preview


我有的:

当鼠标移动时,圆会随机出现在设定的半径上。


我想要的是:

新出现的圆圈在变小时会朝着鼠标移动,而在很小的时候会消失。

可以将其视为某种重力效应,或者将鼠标看作是聚集能量的魔杖。


题:

如何在canvas上实现我想要的?

像这样吗 (有关信息,请参见代码更改)

 var canvas = document.getElementById("canvas"); canvas.width = window.innerWidth; canvas.height = window.innerHeight; var context = canvas.getContext("2d"); function createImageOnCanvas(imageId) { canvas.style.display = "block"; document.getElementById("circles").style.overflowY = "hidden"; var img = new Image(300, 300); img.src = document.getElementById(imageId).src; context.drawImage(img, (0), (0)); //onload.... } var circles = []; var pos = {x:0, y:0}; function draw(e) { context.clearRect(0,0,1000,1000); for(var i=0; i<circles.length; i++) { var circle = circles[i]; var x = circle.x + circle.radius*Math.cos(circle.angle); var y = circle.y + circle.radius*Math.sin(circle.angle); context.fillStyle = "rgba(255,255,255,0.5)"; context.beginPath(); context.arc(x, y, 10 * circle.radius/50, 0, 2*Math.PI); context.fill(); } } // we are storing the mouse position on move // to be used by animation rendering when needed var mouseMoved = false; function onMouseMove(evt) { storeMousePosition(evt); // enable new circle creation mouseMoved = true; } function storeMousePosition(evt) { var rect = canvas.getBoundingClientRect(); pos = { x: evt.clientX - rect.left, y: evt.clientY - rect.top }; } // update positions and sizes of circles // remove ones smaller // create new circles if mouse is moved function updateCircles() { var ncircles = []; for(var i=0; i<circles.length; i++) { var circle = circles[i]; if(circle.radius > 5) { circle.sradius--; if(circle.sradius < 40) { circle.radius--; circle.x = pos.x; circle.y = pos.y; } ncircles.push(circle); } } if(mouseMoved) { // disable creating new circlus // if mouse is stopped mouseMoved = false; posx = pos.x; posy = pos.y; var radius = 50; var angle=Math.random()*Math.PI*2; ncircles.push({ radius: radius, sradius: radius, angle: angle, x: pos.x, y: pos.y }) } circles = ncircles; draw(); } window.draw = draw; // update circles and re-render the frame // in every 40 milliseconds setInterval(updateCircles, 40); 
 canvas { border: 1px solid #000; background-color: black; margin-left: -10px; margin-top: -10px; } 
 <div id="circles"></div> <canvas id="canvas" onmousemove="onMouseMove(event)"></canvas> 

我认为添加一些有关如何满足这种要求的更多信息会很好。

“ ...在变小的同时朝着鼠标移动并消失...”

听起来好像需要一点动画,所以我们需要将“计算”和“渲染”分开,因此我们需要保留对象,它们的颜色,大小,位置等的记录,以渲染“下一帧”。 如果我们不再看到该对象,则可以将其从记录中删除。

在渲染阶段,我们需要获取要渲染的对象数组,并将它们一一绘制到画布上。 但是,在我们需要清除前一帧(或更高级,更改区域的一部分,但现在让我们清除整个画布)之前,请绘制所有内容。 就像在电影中一样,这应该在几秒钟内完成几次。

ps setInterval不是理想的方法,但是由于问题与动画无关,因此我尝试使示例代码中的内容保持简单快捷。 requestAnimationFrame是执行此类操作的更好方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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