HTML5火焰文字效果是一種炫酷的特效,可以為網頁增添很多亮點。下面給大家介紹一段簡單的HTML5火焰文字效果代碼。
首先,在頁面中添加一個畫布標簽canvas。然后,在代碼中定義一個函數,用來生成火焰效果。
function createFire(canvas){ // 火焰效果代碼 } createFire(document.querySelector("#canvas"));在函數里,我們需要定義一些變量,包括畫布的寬度和高度、火焰的像素、漸變色、顏色限制等。
function createFire(canvas){ // 定義畫布的寬度和高度 const width = canvas.offsetWidth; const height = canvas.offsetHeight; // 定義火焰像素值 const firePixelArray = new Array(width * height); for(let i = 0; i< width * height; i++){ firePixelArray[i] = 0; } // 定義顏色限制和漸變色 const colorLimit = 36; const gradient = [ "#070707", "#1f0707", "#2f0f07", "#470f07", "#571707", "#671f07", "#771f07", "#8f2707", "#9f2f07", "#af3f07", "#bf4707", "#c74707", "#DF4F07", "#DF5707", "#DF5707", "#D75F07", "#D75F07", "#D7670F", "#cf6f0f", "#cf770f", "#cf7f0f", "#CF8717", "#C78717", "#C78F17", "#C7971F", "#BF9F1F", "#BF9F1F", "#BFA727", "#BFA727", "#BFAF2F", "#B7AF2F", "#B7B72F", "#B7B737", "#CFCF6F", "#DFDF9F", "#EFEFC7", "#FFFFFF" ]; } createFire(document.querySelector("#canvas"));接著,我們需要創建一個函數用來渲染畫布。
function renderPixel(canvas){ // 定義畫布的寬度和高度 const width = canvas.offsetWidth; const height = canvas.offsetHeight; // 定義像素數據 const ctx = canvas.getContext("2d"); const imageData = ctx.createImageData(width, height); const data = imageData.data; for(let y = 0; y< height; y++){ for(let x = 0; x< width; x++){ const pixelIndex = x + y * width; const colorIndex = firePixelArray[pixelIndex]; const color = gradient[colorIndex]; const colorRGB = hexToRgb(color); data[pixelIndex * 4 + 0] = colorRGB.r; data[pixelIndex * 4 + 1] = colorRGB.g; data[pixelIndex * 4 + 2] = colorRGB.b; data[pixelIndex * 4 + 3] = 255; } } ctx.putImageData(imageData, 0, 0); } createFire(document.querySelector("#canvas")); renderPixel(document.querySelector("#canvas"));最后,我們需要創建一個函數用來循環渲染畫布,并將其整合到火焰效果函數中。
function createFire(canvas){ // 定義畫布的寬度和高度 const width = canvas.offsetWidth; const height = canvas.offsetHeight; // 定義火焰像素值 const firePixelArray = new Array(width * height); for(let i = 0; i< width * height; i++){ firePixelArray[i] = 0; } // 定義顏色限制和漸變色 const colorLimit = 36; const gradient = [ // 顏色值 ]; // 定義渲染畫布的函數 function renderPixel(canvas){ // 渲染畫布的代碼 } // 定義循環渲染畫布的函數 function loop(){ for(let y = 0; y< height - 1; y++){ for(let x = 0; x< width; x++){ const pixelIndex = x + y * width; updateFireIntensityPerPixel(pixelIndex); } } renderPixel(canvas); window.requestAnimationFrame(loop); } function updateFireIntensityPerPixel(currentPixelIndex){ const belowPixelIndex = currentPixelIndex + width; if(belowPixelIndex >= width * height) return; const decay = Math.floor(Math.random() * 3); const belowPixelFireIntensity = firePixelArray[belowPixelIndex]; const newFireIntensity = belowPixelFireIntensity - decay >= 0 ? belowPixelFireIntensity - decay : 0; firePixelArray[currentPixelIndex - decay] = newFireIntensity; } // 循環渲染畫布 window.requestAnimationFrame(loop); } createFire(document.querySelector("#canvas"));這段代碼可以生成一個簡單的HTML5火焰文字效果。如果想要讓效果更加炫酷,可以加入音效或者添加交互等功能。