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)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
JavaScript的Object.defineProperty詳解
本篇文章給大家詳細講述了JavaScript的Object.defineProperty的相關(guān)知識點內(nèi)容,有興趣的朋友參考學(xué)習(xí)下。2018-07-07
JavaScript?防抖debounce與節(jié)流thorttle
這篇文章主要介紹了JavaScript?防抖debounce與節(jié)流thorttle,文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-05-05
JavaScript使用docx-preview和mammoth預(yù)覽Docx
這篇文章主要為大家詳細介紹了兩個庫,即docx-preview和mammoth,利用它們,你就能在瀏覽器中完美預(yù)覽 Word 文檔,甚至連表格樣式,頁眉頁腳都原汁原味地呈現(xiàn)出來,下面我們來看看具體使用步驟吧2025-04-04
JavaScript+Canvas實現(xiàn)彩色圖片轉(zhuǎn)換成黑白圖片的方法分析
這篇文章主要介紹了JavaScript+Canvas實現(xiàn)彩色圖片轉(zhuǎn)換成黑白圖片的方法,結(jié)合實例形式分析了javascript結(jié)合HTML5相關(guān)函數(shù)修改頁面圖片元素顯示效果相關(guān)操作技巧,需要的朋友可以參考下2018-07-07
前端微信H5公眾號實現(xiàn)授權(quán)登錄的方法總結(jié)
這篇文章主要介紹了如何在微信公眾號中實現(xiàn)網(wǎng)頁授權(quán)功能,包括創(chuàng)建微信服務(wù)公眾號、配置重定向地址、調(diào)試和開發(fā)使用等步驟,文中通過圖文及代碼介紹的非常詳細,需要的朋友可以參考下2025-01-01
javascript學(xué)習(xí)隨筆(使用window和frame)的技巧
javascript學(xué)習(xí)隨筆(使用window和frame)的技巧...2007-03-03
JavaScript實現(xiàn)Tab標簽頁切換的最簡便方式(4種)
這篇文章主要介紹了JavaScript實現(xiàn)Tab標簽頁切換的最簡便方式(4種),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-06-06

