Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use canvas to realize the dynamic effect of background Mouse connection

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "how to use canvas to achieve the dynamic effect of background mouse connection". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to use canvas to achieve the dynamic effect of background mouse connection".

HTML code (test code):

Canvas scene connection special effects * {margin: 0px; padding: 0px;} body {background-color: # f4f4f4;}

Javascript Code:

/ / execute the function immediately /! Is to tell the javascript engine that this is a function expression, not a function declaration, (),! Operators such as +, +, -, and so on can do this, but () is the safest / / in! function () {} followed by () immediately calls this function / / this imitates a private scope, so that html files reference multiple js files without variable conflicts! function () {/ / canvas element related / / create canvas element And set the canvas element id var canvas = document.createElement ("canvas"), context = canvas.getContext ("2d"), attr = getAttr () / / set the relevant attributes of the created canvas canvas.id = "cymn" + attr.length; canvas.style.cssText = "position:fixed;top:0;left:0;z-index:" + attr.z + "; opacity:" + attr.opacity; / / add the canvas element to the body element document.getElementsByTagName ("body") [0] .appendChild (canvas) / / this function sets the width attribute of the canvas element and the height attribute getWindowWH (); / / the onresize event occurs when the window or frame is resized. / / here, when the window size changes, re-obtain the width and height of the window and set the width and height of the canvas element _ window.onresize = getWindowWH. / / this function will get the script element referencing this file, / / because the getScript function is executed once during assignment in this file, and when the html file references this file, the script tag after this file has not been interpreted by the browser, / / so in the resulting script array The script element of this article is referenced at the end of the array / / the function is intended to enable developers to directly modify the attributes of the script element that introduced the file in html to modify some attributes of the canvas, the z-index, transparency and number of squares of the canvas, color / / with the previous code that added the canvas element to the body element, when the developer wants to use the special effect as the background Simply add the script element to the html file and reference this file to function getAttr () {let scripts = document.getElementsByTagName ("script"), len = scripts.length, script = scripts [len-1] / / v is the last script element That is, return {length: len, z: script.getAttribute ("zIndex") | |-1, opacity: script.getAttribute ("opacity") | | 0.5, color: script.getAttribute ("color") | | "count: script.getAttribute (" count ") | | 99}} / / to obtain the window width and height. And set the width and height of canvas element function getWindowWH () {W = canvas.width = window.innerWidth | | document.documentElement.clientWidth | | document.body.clientWidth, H = canvas.height = window.innerHeight | | document.documentElement.clientHeight | | document.body.clientHeight} / / generate small squares at random positions var random = Math.random, squares = [] / / store small squares / / put small squares for (let p = 0; p) into the squares [] array

< attr.count; p++) { var square_x = random() * W, //横坐标 square_y = random() * H, //纵坐标 square_xa = 2 * random() - 1, //x轴位移 -1,1 square_ya = 2 * random() - 1; //y轴位移 squares.push({ x: square_x, y: square_y, xa: square_xa, ya: square_ya, max: 6000 }) } //生成鼠标小方块 var mouse = { x: null, y: null, max: 20000 }; //获取鼠标所在坐标 _window.onmousemove = function(i) { //i为W3C DOM,window.event 为 IE DOM,以实现兼容IE //不过目前似乎IE已经支持W3C DOM,我用的是IE11,我注释掉下一句代码也能实现鼠标交互效果, //网上说7/8/9是不支持的,本人没有试验, //当然加上是没有错的 i = i || window.event; mouse.x = i.clientX; mouse.y = i.clientY; } //鼠标移出窗口后,消除鼠标小方块 _window.onmouseout = function() { mouse.x = null; mouse.y = null; } //绘制小方块,小方块移动(碰到边界反向移动),小方块受鼠标束缚 var animation = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(i) { window.setTimeout(i, 1000 / 45) }; //各个浏览器支持的requestAnimationFrame有所不同,兼容各个浏览器 function draw() { //清除画布 context.clearRect(0, 0, W, H); var w = [mouse].concat(squares); //连接(合并)鼠标小方块数组和其他小方块数组 var x, v, A, B, z, y; //square属性表:x,y,xa,ya,max squares.forEach(function(i) { //实现小方块定向移动 i.x += i.xa; i.y += i.ya; // 控制小方块移动方向 // 当小方块达到窗口边界时,反向移动 i.xa = i.xa * (i.x >

W | | i.x

< 0 ? -1 : 1); i.ya = i.ya * (i.y >

H | | I.Y

< 0 ? -1 : 1); //fillRect前两个参数为矩形左上角的x,y坐标,后两个分别为宽度和高度 //绘制小方块 context.fillRect(i.x - 0.5, i.y - 0.5, 1, 1); //遍历w中所有元素 for (let n = 0; n < w.length; n++) { x = w[n]; //如果x与i不是同一个对象实例且x的xy坐标存在 if (i !== x && null !== x.x && null !== x.y) { x_diff = i.x - x.x; //i和x的x坐标差 y_diff = i.y - x.y; //i和x的y坐标差 distance = x_diff * x_diff + y_diff * y_diff; //斜边平方 if (distance < x.max) { //使i小方块受鼠标小方块束缚,即如果i小方块与鼠标小方块距离过大,i小方块会被鼠标小方块束缚, //造成 多个小方块以鼠标为圆心,mouse.max/2为半径绕成一圈 if (x === mouse && distance >

X.max / 2) {i.x = i.x-0.03 * x diffused; i.y = i.y-0.03 * y diffused;} A = (x.max-distance) / x.max; context.beginPath () / / set the thickness of the drawing line of the brush is related to the distance between the two small squares, ranging from 0 to 0.5. the farther the distance between the two small squares, the thinner the line is drawn, and when it reaches max, the line disappears context.lineWidth = A / 2 / / set the brush line color to s.c, that is, canvas color, and transparency = "rgba (" + attr.color + "," + (Aban 0.2) + ")". / / set the stroke of the brush to I square context.moveTo (i.x, i.y); / / move the brush stroke to the x square context.lineTo (x.x, x.y) / / complete the drawing of the line, that is, draw the line connecting the small square context.stroke () } / / remove I squares from the w array / / prevent two squares from reconnecting w.splice (w.indexOf (I), 1);}) / / window.requestAnimationFrame is similar to setTimeout, resulting in recursive calls, / / but window.requestAnimationFrame uses the system interval to maintain the best rendering efficiency, providing better optimization and smoother animation / / optimized by the browser, the animation is smoother. / / when the window is not activated, the animation will stop, saving computing resources; animation (draw);} / / after waiting for 0.1s, execute draw (). The real animation effect is setTimeout (function () {draw ();}, 100)} () implemented in window.requestAnimationFrame. Thank you for reading, the above is the content of "how to use canvas to achieve the dynamic effect of background mouse connection". After the study of this article, I believe you have a deeper understanding of how to use canvas to achieve the dynamic effect of background mouse connection, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report