使用getImageData介面取得圖片的像素點,然後基於像素點實現動畫效果,封裝成一個簡單的lib
<!DOCTYPE html> <html> <head> <title>particle image</title> <meta charset="utf-8" /> <style> #logo { margin-left:20px; margin-top:20px; width:160px; height:48px; background:url('./images/logo.png'); /*border: 1px solid red;*/ } </style> <script type="text/javascript" src="ParticleImage.js"></script> <script> window.onload = function() { ParticleImage.create("logo", "./images/logo.png", "fast"); }; </script> </head> <body> <div id="logo"></div> </body> </html>
ParticleImage.js
/* The MIT License (MIT) Copyright (c) 2015 arest Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * Add particle animation for image * usage: <script type="text/javascript" src="ParticleImage.js"></script> <script> window.onload = function() { // be sure to use image file in your own server (prevent CORS issue) ParticleImage.create("logo", "logo_s2.png", "fast"); }; </script> // in html file <div id="logo"></div> // you can set default background image as usual #logo { margin-left:20px; margin-top:20px; width:160px; height:48px; background:url('logo_s2.png'); } * * @author tianx.qin (rushi_wowen@163.com) * @file ParticleImage.js * @version 0.9 */ var ParticleImage = (function(window) { var container = null, canvas = null; var ctx = null, _spirit = [], timer = null, cw = 0, ch = 0, // container width/height iw = 0, ih = 0, // image width/height mx = 0, my = 0, // mouse position bMove = true, MOVE_SPAN = 4, DEFAULT_ALPHA = 100, speed = 100, S = {"fast":10, "mid":100, "low":300}, ALPHA = 255 * 255; // spirit class var Spirit = function(data) { this.orginal = { pos: data.pos, x : data.x, y : data.y, r : data.r, g : data.g, b : data.b, a : data.a }; // change state, for animation this.current = { x : data.x, y : data.y, a : data.a }; }; /** * move spirit to original position */ Spirit.prototype.move = function() { var cur = this.current, orig = this.orginal; if ((cur.x === orig.x) && (cur.y === orig.y)) { //console.log("don't move:" + cur.y); return false; } //console.log("move:" + cur.y); var rand = 1 + Math.round(MOVE_SPAN * Math.random()); var offsetX = cur.x - orig.x, offsetY = cur.y - orig.y; var rad = offsetX == 0 ? 0 : offsetY / offsetX; var xSpan = cur.x < orig.x ? rand : cur.x > orig.x ? -rand : 0; cur.x += xSpan; var tempY = xSpan == 0 ? Math.abs(rand) : Math.abs(Math.round(rad * xSpan)); var ySpan = offsetY < 0 ? tempY : offsetY > 0 ? -tempY : 0; cur.y += ySpan; cur.a = ((cur.x === orig.x) && (cur.y === orig.y)) ? orig.a : DEFAULT_ALPHA; return true; }; /** * set random position */ Spirit.prototype.random = function(width, height) { var cur = this.current; cur.x = width + Math.round(width * 2 * Math.random()); this.current.y = height + Math.round(height * 2 * Math.random()); }; /** * set random positions for all spirits */ var _disorder = function() { var len = _spirit.length; for (var i = 0; i < len; i++) { _spirit[i].random(cw, ch); } }; /** * start to move spirit */ var _move = function() { var sprt = _spirit; var len = sprt.length; var isMove = false; // whether need to move for (var i = 0; i < len; i++) { if (sprt[i].move()) { isMove = true; } } isMove ? _redraw() : _stopTimer(); }; /** * redraw all spirits while animating */ var _redraw = function() { var imgDataObj = ctx.createImageData(iw, ih); var imgData = imgDataObj.data; var sprt = _spirit; var len = sprt.length; //console.log("redraw image : " + len); for (var i = 0; i < len; i++) { var temp = sprt[i]; //console.log("item : " + JSON.stringify(temp)); var orig = temp.orginal; var cur = temp.current; var pos = (cur.y * iw + cur.x) * 4; imgData[pos] = orig.r; imgData[pos + 1] = orig.g; imgData[pos + 2] = orig.b; imgData[pos + 3] = cur.a; } ctx.putImageData(imgDataObj, 0, 0); }; /** * add mousemove/mouseclick event */ var _addMouseEvent = function(c) { c.addEventListener("mouseenter", function(e) { //console.log("e.y:" + e.clientY + ", " + container.offsetTop); _startTimer(); }); c.addEventListener("click", function() { // disorder all spirits and start animation _startTimer(); }); }; /** * calculate all pixels of the logo image */ var _checkImage = function(imgUrl, callback) { // var tempCanvas = document.getElementById("temp"); //canvas.width = width; //canvas.height = height; var proc = function(image) { var w = image.width, h = image.height; iw = w, ih = h; //console.log("proc image " + image + "," + w + "," + h); canvas = _createCanvas(); // hide container background container.style.backgroundPosition = (-w) + "px"; container.style.backgroundRepeat = "no-repeat"; ctx.drawImage(image, 0, 0); // this may cause security error for CORS issue try { var imgData = ctx.getImageData(0, 0, w, h); var arrData = imgData.data; for (var i = 0; i < arrData.length; i += 4) { var r = arrData[i], g = arrData[i + 1], b = arrData[i + 2], a = arrData[i + 3]; if (r > 0 || g > 0 || b > 0 || a > 0) { var pos = i / 4; _spirit.push(new Spirit({ x : pos % w, y : Math.floor(pos / w), r : r, g : g, b : b, a : a })); } } return true; } catch (e) { // do nothing return false; } //return out; }; var img = new Image(); img.src = imgUrl; if (img.complete || img.complete === undefined) { proc(img) && callback && callback(); } else { img.onload = function() { proc(img) && callback && callback(); }; } }; // use "requestAnimationFrame" to create a timer, need browser support var _timer = function(func, dur) { //console.log("speed is " + dur); var timeLast = null; var bStop = false; var bRunning = false; // prevent running more than once var _start = function() { if (func) { if (! timeLast) { timeLast = Date.now(); func(); } else { var current = Date.now(); if (current - timeLast >= dur) { timeLast = current; func(); } } } if (bStop) { return; } requestAnimationFrame(_start); }; var _stop = function() { bStop = true; }; return { start : function() { if (bRunning) { //console.log("already running.."); return; } //console.log("start running.."); bRunning = true; bStop = false; _disorder(); _start(); }, stop : function() { _stop(); bRunning = false; } }; }; var _startTimer = function() { if (! timer) { timer = _timer(function() { bMove && _move(); }, speed); } timer.start(); }; var _stopTimer = function() { timer && timer.stop(); }; /** * start process */ var _create = function(imgUrl) { _checkImage(imgUrl, function() { //_createSpirits(); _addMouseEvent(canvas); //_startTimer(); }); }; var _setSpeed = function(s) { S[s] && (speed = S[s]); }; /** * check whether browser supports canvas */ var _support = function() { try { document.createElement("canvas").getContext("2d"); return true; } catch (e) { return false; } }; /** * create a canvas element */ var _createCanvas = function() { var cav = document.createElement("canvas"); cav.width = iw; cav.height = ih; container.appendChild(cav); ctx = cav.getContext("2d"); return cav; }; /** * initialize container params */ var _init = function(c, s) { if ((! c) || (! _support())) { // DIV id doesn't exist return false; } container = c; cw = c.clientWidth; ch = c.clientHeight; s && _setSpeed(s); return true; }; /** * export */ return { "create" : function(cId, imgUrl, s) { // user can set move speed by 's'['fast','mid','low'] _init(document.getElementById(cId), s) && _create(imgUrl); } }; })(window);
以上所述就是本文的全部內容了,希望大家能夠喜歡。

理解JavaScript引擎內部工作原理對開發者重要,因為它能幫助編寫更高效的代碼並理解性能瓶頸和優化策略。 1)引擎的工作流程包括解析、編譯和執行三個階段;2)執行過程中,引擎會進行動態優化,如內聯緩存和隱藏類;3)最佳實踐包括避免全局變量、優化循環、使用const和let,以及避免過度使用閉包。

Python更適合初學者,學習曲線平緩,語法簡潔;JavaScript適合前端開發,學習曲線較陡,語法靈活。 1.Python語法直觀,適用於數據科學和後端開發。 2.JavaScript靈活,廣泛用於前端和服務器端編程。

Python和JavaScript在社區、庫和資源方面的對比各有優劣。 1)Python社區友好,適合初學者,但前端開發資源不如JavaScript豐富。 2)Python在數據科學和機器學習庫方面強大,JavaScript則在前端開發庫和框架上更勝一籌。 3)兩者的學習資源都豐富,但Python適合從官方文檔開始,JavaScript則以MDNWebDocs為佳。選擇應基於項目需求和個人興趣。

從C/C 轉向JavaScript需要適應動態類型、垃圾回收和異步編程等特點。 1)C/C 是靜態類型語言,需手動管理內存,而JavaScript是動態類型,垃圾回收自動處理。 2)C/C 需編譯成機器碼,JavaScript則為解釋型語言。 3)JavaScript引入閉包、原型鍊和Promise等概念,增強了靈活性和異步編程能力。

不同JavaScript引擎在解析和執行JavaScript代碼時,效果會有所不同,因為每個引擎的實現原理和優化策略各有差異。 1.詞法分析:將源碼轉換為詞法單元。 2.語法分析:生成抽象語法樹。 3.優化和編譯:通過JIT編譯器生成機器碼。 4.執行:運行機器碼。 V8引擎通過即時編譯和隱藏類優化,SpiderMonkey使用類型推斷系統,導致在相同代碼上的性能表現不同。

JavaScript在現實世界中的應用包括服務器端編程、移動應用開發和物聯網控制:1.通過Node.js實現服務器端編程,適用於高並發請求處理。 2.通過ReactNative進行移動應用開發,支持跨平台部署。 3.通過Johnny-Five庫用於物聯網設備控制,適用於硬件交互。

我使用您的日常技術工具構建了功能性的多租戶SaaS應用程序(一個Edtech應用程序),您可以做同樣的事情。 首先,什麼是多租戶SaaS應用程序? 多租戶SaaS應用程序可讓您從唱歌中為多個客戶提供服務

本文展示了與許可證確保的後端的前端集成,並使用Next.js構建功能性Edtech SaaS應用程序。 前端獲取用戶權限以控制UI的可見性並確保API要求遵守角色庫


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

禪工作室 13.0.1
強大的PHP整合開發環境

記事本++7.3.1
好用且免費的程式碼編輯器

Safe Exam Browser
Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

WebStorm Mac版
好用的JavaScript開發工具

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),