如何在Canvas中创建类似电视噪音的背景

如何在Canvas中创建类似电视噪音的背景

电视噪音是在电视机或其他设备的接收天线没有接收到传输信号时显示的随机黑白点像素图案。要将这种情景作为背景创建,我们将需要使用HTML、CSS和JavaScript。HTML用于创建画布区域,或者您可以将整个背景用作区域。CSS将用于设计背景,而JavaScript将创建电视噪音动画。我们将逐步完成此任务。以下步骤分别列出并描述了每一步。

如何在Canvas中创建类似电视噪音的背景

示例:

HTML代码

<!DOCTYPE html> 
<html lang="en"> 
  
<head> 
    <meta charset="utf-8"> 
    <title>TV noise Background</title> 
</head> 
  
<body> 
    <canvas id="canvas"></canvas> 
    <h1>GeeksforGeeks</h1> 
    <h2>A Computer Science Portal for Geeks</h2> 
    <h3>Animated TV noise Background</h3> 
</body> 
  
</html> 
HTML

CSS代码

<style>  
    #canvas { 
        z-index: -100; 
        position: absolute; 
        top: 0; 
        left: 0; 
        opacity: 0.8; 
        background-color: #fff; 
    } 
    h1 { 
        color: green; 
        font-size: 50px; 
        margin-bottom: 0; 
    } 
    body { 
        text-align: center; 
    } 
</style>
CSS

JavaScript代码

<script> 
    var canvas = document.getElementById('canvas'), 
               
    /* The getContext() method returns an object  
    that provides methods and properties for  
    drawing on the canvas. */
    ctx = canvas.getContext('2d'); 
   
    /* Setting canvas width and height equal to 
    window screen width and height. */
    function resize() { 
        canvas.width = window.innerWidth; 
        canvas.height = window.innerHeight; 
    } 
    resize(); 
    window.onresize = resize; 
   
    // Function to generate noise effect 
    function generate_noise(ctx) { 
        var w = ctx.canvas.width, 
        h = ctx.canvas.height, 
                   
        /* This creates a new ImageData object 
        with the specified dimensions(i.e canvas 
        width and height). All pixels are set to 
        transparent black (i.e rgba(0,0,0,0)). */
        idata = ctx.createImageData(w, h),  
                   
        // Creating Uint32Array typed array 
        buffer32 = new Uint32Array(idata.data.buffer),  
        buffer_len = buffer32.length, 
        i = 0 
          
        for ( ; i < buffer_len; i++) 
            buffer32[i] =  
                ((255 * Math.random()) | 0) << 24; 
               
        /* The putImageData() method puts the image 
        data (from a specified ImageData object) 
        back onto the canvas. */
        ctx.putImageData(idata, 0, 0);  
    } 
   
    // Creating animation effect 
    var toggle = true; 
    (function loop() { 
        toggle = !toggle; 
        if (toggle) { 
               
            // Loop function is called each time 
            // before next repaint. 
            requestAnimationFrame(loop);  
            return; 
        } 
    generate_noise(ctx); 
    requestAnimationFrame(loop); 
    })(); 
</script>
JavaScript

输出:

如何在Canvas中创建类似电视噪音的背景

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册