我目前拥有的是很多html元素,以及jQuery和css来创建一个基于鼠标移动效果的点阵图案.很难解释所以我做了一个例子. http://jsfiddle.net/sebastianscholten/u6ebt390/
var mX,mY,distance;
function theDistance(elem,mouseX,mouseY) {
return Math.floor(Math.sqrt(Math.pow(mouseX - (elem.offset().left+(elem.width()/2)),2) + Math.pow(mouseY - (elem.offset().top+(elem.height()/2)),2)));
}
$(document).mousemove(function(e) {
mX = e.pageX;
mY = e.pageY;
cutoff = 100;
$('.element').each(function(){
distance = theDistance($(this),mX,mY);
if (distance <= cutoff) {
$(this).css('transform','scale(' + (distance*(1/cutoff)-1) + ')');
} else {
$(this).css('transform','scale(0)');
}
});
});
问题是性能有问题,所以我想用html画布制作相同的效果.我不知道它是否会起作用.
你们知道其他任何方式我可以创建相同的效果,没有很多的HTML元素.谢谢.
编辑:感谢markE的回答.这对我帮助很大.这就是我想出来的.
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
var circleRadius = 1;
var circleMargin = 10;
var canvasW = c.width;
var canvasH = c.height;
var $canvas = $("#canvas");
var canvasOffset = $canvas.offset();
var offsetX = canvasOffset.left;
var offsetY = canvasOffset.top;
var circleAmountX = canvasW / (circleRadius + (2 * circleMargin));
var circleAmountY = canvasH / (circleRadius + (2 * circleMargin));
function draw(mouseX,mouseY) {
ctx.clearRect(0,canvasW,canvasH);
for (i = 0; i < circleAmountX + 1; i++) {
for (k = 0; k < circleAmountY + 1; k++) {
var x = i * (circleRadius + circleMargin * 2);
var y = k * (circleRadius + circleMargin * 2);
var dx = mouseX - x;
var dy = mouseY - y;
var inflation = 1;
var inflationAmount = 6;
var cutoff = 150;
var distance = Math.sqrt(dx * dx + dy * dy);
if (distance <= cutoff && distance > 0) {
inflation = inflationAmount - (distance / ((cutoff / inflationAmount) + 2));
} else if (distance = 0) {
inflation = inflationAmount;
}
ctx.beginPath();
ctx.arc(x,y,circleRadius * inflation,2 * Math.PI);
ctx.fill();
ctx.closePath();
}
}
}
draw(0,0);
$("#canvas").mousemove(function (e) {
var mX = parseInt(e.clientX - offsetX);
var mY = parseInt(e.clientY - offsetY);
draw(mX,mY);
});
最佳答案
是的,您可以使用画布获得更好的性能:
原文链接:https://www.f2er.com/html/426089.html>听取mousemove事件
>计算鼠标和鼠标之间的距离.圆心:
var dx=mouseX-centerX;
var dy=mouseY-centerY;
var distance=Math.sqrt(dx*dx+dy*dy);
>根据鼠标与圆圈的接近程度重新绘制膨胀/缩小的圆圈
祝你的项目好运!
这是一个带有1个圆圈的概念验证:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var $canvas=$("#canvas");
var canvasOffset=$canvas.offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
var cx=150;
var cy=150;
var radius=30;
var inflation=.25;
draw();
$("#canvas").mousemove(function(e){handleMouseMove(e);});
function draw(){
ctx.clearRect(0,canvas.width,canvas.height);
ctx.beginPath();
ctx.arc(150,150,inflation,Math.PI*2);
ctx.closePath();
ctx.fill();
ctx.stroke();
}
function handleMouseMove(e){
e.preventDefault();
e.stopPropagation();
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
var dx=mouseX-cx;
var dy=mouseY-cy;
var distance=Math.sqrt(dx*dx+dy*dy);
if(distance
body{ background-color: ivory; }
#canvas{border:1px solid red;}