用 Canvas 画简易手电筒

本文章适合人群:

  • 具备 html、js 基础的人
  • 对于想入门 canvas 的人

本文章较为简单,大佬可略过

实验结果

一个跟随着鼠标移动的圆圈。
在这里插入图片描述

教学

要实现一个动态手电筒效果,我们可以使用Canvas来绘制一个黑色的遮罩层,并通过鼠标或触摸事件来控制光圈的位置和大小。 首先,我们需要在HTML中创建一个Canvas元素和一个用于控制光圈的滑块。

<canvas id="flashlightCanvas"></canvas>
<input type="range" id="lightSize" min="50" max="200" value="100"> 

接下来,在JavaScript中获取Canvas元素和滑块的引用,并设置Canvas的宽度和高度。

const canvas = document.getElementById("flashlightCanvas"); 
const ctx = canvas.getContext("2d"); 
canvas.width = window.innerWidth; 
canvas.height = window.innerHeight; 

然后,我们需要创建一个函数来绘制遮罩层和光圈。该函数会在滑块值改变和鼠标/触摸事件发生时被调用。

function drawFlashlight() { 
  // 清除画布 
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  // 绘制黑色遮罩层 
  ctx.fillStyle = "rgba(0, 0, 0, 0.7)";
  ctx.fillRect(0, 0, canvas.width, canvas.height); 
  // 获取光圈位置和大小 
  const lightSize = document.getElementById("lightSize").value; 
  const mouseX = event.clientX; const mouseY = event.clientY; 
  // 绘制光圈 
  ctx.globalCompositeOperation = "destination-out"; 
  ctx.beginPath(); 
  ctx.arc(mouseX, mouseY, lightSize, 0, Math.PI * 2); 
  ctx.fill(); 
  ctx.globalCompositeOperation = "source-over";
} 

最后,我们需要为滑块和鼠标/触摸事件添加事件监听器,并在事件发生时调用绘制函数。

document.getElementById("lightSize").addEventListener("input", drawFlashlight); 
canvas.addEventListener("mousemove", drawFlashlight); canvas.addEventListener("touchmove", drawFlashlight); 

现在,当滑块值改变或鼠标/触摸事件发生时,光圈会在Canvas上绘制出来,实现动态手电筒效果。

完整代码

<!DOCTYPE html>
<html>

<head>
    <title>Dynamic Flashlight</title>
    <style>
        body {
            margin: 0;
            overflow: hidden;
        }
    </style>
</head>

<body>
    <canvas id="flashlightCanvas"></canvas>
    <input type="range" id="lightSize" min="50" max="200" value="100">
    <script>
        const canvas = document.getElementById("flashlightCanvas");
        const ctx = canvas.getContext("2d");
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
        function drawFlashlight() {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            ctx.fillStyle = "rgba(0, 0, 0, 0.7)";
            ctx.fillRect(0, 0, canvas.width, canvas.height);
            const lightSize = document.getElementById("lightSize").value;
            const mouseX = event.clientX; const mouseY = event.clientY;
            ctx.globalCompositeOperation = "destination-out"; ctx.beginPath();
            ctx.arc(mouseX, mouseY, lightSize, 0, Math.PI * 2); ctx.fill();
            ctx.globalCompositeOperation = "source-over";
        }
        document.getElementById("lightSize").addEventListener("input", drawFlashlight);
        canvas.addEventListener("mousemove", drawFlashlight);
        canvas.addEventListener("touchmove", drawFlashlight); 
    </script>
</body>
</html>
posted @ 2023-09-14 18:52  辰梦starDream  阅读(12)  评论(0编辑  收藏  举报  来源