react+canvas实现刮刮乐效果


话不多说,直接看代码吧
cpp 复制代码
import { useEffect } from 'react';
import styles from './index.less';

export default function Canvas() {
  function init() {
    let gj = document.querySelector('.gj');
    let jp = document.querySelector('#jp') as HTMLElement;
    let canvas = document.querySelector('#mask') as HTMLCanvasElement;
    let ctx = canvas?.getContext('2d') as any;
	// 遮罩层mask设置
    ctx.fillStyle = '#e0e0e0';
    ctx.fillRect(0, 0, 200, 100);
    ctx.fillStyle = '#ffffff';
    ctx.font = '16px 微软雅黑';
    ctx?.fillText('刮奖区', 80, 50); // 文字在框中位置

	// 奖品部分逻辑
    let arr = ['一等奖', '二等奖', '三等奖', '再来一次'];
    let randomNum = Math.random() * 100;
    if (randomNum < 10) {
      jp.innerHTML = arr[0];
    } else if (randomNum < 30) {
      jp.innerHTML = arr[1];
    } else if (randomNum < 60) {
      jp.innerHTML = arr[2];
    } else {
      jp.innerHTML = arr[3];
    }
	// 绘图部分
    let isDraw = false;
    canvas.onmousedown = () => (isDraw = true);
    canvas.onmouseup = () => (isDraw = false);
    canvas.onmousemove = (e) => {
      if (isDraw) {
        writeText(ctx, e, gj);
      }
    };
  } 
  function writeText(ctx: any, e: MouseEvent, gj: HTMLElement) {
    ctx?.beginPath();
    let x = e.pageX - gj?.getBoundingClientRect().left;
    let y = e.pageY - gj?.getBoundingClientRect().top;
    ctx.globalCompositeOperation = 'destination-out'; // !!! 在后绘制的图形上方显示先绘制的图形, 相交部分由先绘制图形的填充(颜色,渐变,纹理)覆盖
    ctx?.closePath();
    ctx?.arc(x, y, 10, 0, Math.PI * 2);
    ctx?.fill();
  }
  useEffect(() => {
    init();
  }, []);
  return (
    <div className={styles.container}>
      <div className="  text-center  text-[16px]">刮刮乐</div>
      <div className="gj mt-4 cursor-pointer">
        <div id="jp"></div>
        <canvas id="mask" width={200} height={100}></canvas>
      </div>
    </div>
  );
}
cpp 复制代码
index.less部分
.container {
  padding: 20px;
  box-shadow: 4px 4px 4px 4px #eee;
  overflow: hidden; 
    .gj {
      margin: 16px auto;
      width: 200px;
      height: 100px;
      #jp {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        font-size: 20px;
        color: black;
      }
      #mask {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
      }
    } 
}
相关推荐
PineappleCoder3 小时前
还在重复下载资源?HTTP 缓存让二次访问 “零请求”,用户体验翻倍
前端·性能优化
拉不动的猪3 小时前
webpack编译中为什么不建议load替换ast中节点删除consolg.log
前端·javascript·webpack
李姆斯3 小时前
Agent时代下,ToB前端的UI和交互会往哪走?
前端·agent·交互设计
源码获取_wx:Fegn08953 小时前
基于springboot + vue健身房管理系统
java·开发语言·前端·vue.js·spring boot·后端·spring
闲谈共视4 小时前
基于去中心化社交与AI智能服务的Web钱包商业开发的可行性
前端·人工智能·去中心化·区块链
CreasyChan4 小时前
C# 反射详解
开发语言·前端·windows·unity·c#·游戏开发
JIngJaneIL4 小时前
基于Java+ vue智慧医药系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot
阿蒙Amon5 小时前
JavaScript学习笔记:6.表达式和运算符
javascript·笔记·学习
hashiqimiya6 小时前
两个步骤,打包war,tomcat使用war包
java·服务器·前端
小a杰.6 小时前
Flutter 设计系统构建指南
开发语言·javascript·ecmascript