JavaScript canvas實現(xiàn)跟隨鼠標事件
更新時間:2020年02月10日 13:47:06 作者:哪天才能學到vue
這篇文章主要為大家詳細介紹了JavaScript canvas實現(xiàn)跟隨鼠標事件,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了用canvas實現(xiàn)跟隨鼠標事件的具體代碼,供大家參考,具體內(nèi)容如下
//鼠標移動 展現(xiàn)光片

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
body {
margin: 0;
overflow: hidden;
}
#canvas {
background: #000;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var circleList = [];
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
canvas.addEventListener('mousemove', function (e) {
// 將對象push到數(shù)組中,畫出來的彩色小點可以看作每一個對象中記錄著信息 然后存在數(shù)組中
circleList.push(new Circle(e.clientX, e.clientY));
})
//取x到y(tǒng)之間隨機數(shù):Math.round(Math.random()*(y-x)+x) 包括y
function random(min, max) {
return Math.round(Math.random() * (max - min) + min);
}
function Circle(x, y) {
this.x = x;
this.y = y;
this.vx = (Math.random() - 0.5) * 3; //隨機出來一個正數(shù),或者負數(shù)。乘3是為了讓速度變得大一點
this.vy = (Math.random() - 0.5) * 3;
this.color = 'rgb(' + random(0, 255) + ',' + random(0, 255) + ',' + random(0, 255) + ')';
this.a = 1; // 初始透明度
this.draw();
}
Circle.prototype = {
draw() {
context.beginPath();
context.fillStyle = this.color;
context.globalCompositeOperation = 'lighter';
context.globalAlpha = this.a; //全局透明度
context.arc(this.x, this.y, 30, 0, Math.PI * 2, false);
context.fill();
this.update();
},
update() {
// 根據(jù)速度更新每一個小圓的位置
this.x += this.vx;
this.y += this.vy;
this.a *= 0.98;
}
}
function render() {
//把原來的內(nèi)容區(qū)域清除掉
context.clearRect(0, 0, canvas.width, canvas.height);
circleList.forEach(function (ele, i) {
ele.draw();
if (ele.a < 0.05) {
circleList.splice(i, 1);
}
});
requestAnimationFrame(render); //動畫,會根據(jù)瀏覽器的刷新頻率更新動畫
}
render();
</script>
</body>
</html>
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
IE6-IE9不支持table.innerHTML的解決方法分享
讓ie6-ie9支持table.innerHTML,其實這里只是對table做了處理,對其他不支持的元素可以用類似的方案2012-09-09
html2canvas屬性和使用方法以及如何使用html2canvas將HTML內(nèi)容寫入Canvas生成圖片
為大家介紹一款JS截圖插件html2canvas.js, 它可以通過純JS對瀏覽器端經(jīng)行截屏,下面就為大家介紹一下html2canvas.js屬性和具體使用方法,并為大家提供了一個實例2020-01-01
javascript實現(xiàn)數(shù)組最大值和最小值的6種方法
比較數(shù)組中數(shù)值的大小是比較常見的操作,本文主要介紹了javascript實現(xiàn)數(shù)組最大值和最小值的6種方法,需要的朋友們下面隨著小編來一起學習學習吧2021-05-05
JS實現(xiàn)不使用圖片仿Windows右鍵菜單效果代碼
這篇文章主要介紹了JS實現(xiàn)不使用圖片仿Windows右鍵菜單效果代碼,涉及文鼎字及css樣式的使用技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-10-10
javascript ASCII和Hex互轉的實現(xiàn)方法
下面小編就為大家?guī)硪黄猨avascript ASCII和Hex互轉的實現(xiàn)方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-12-12

