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%);
      }
    } 
}
相关推荐
码事漫谈3 分钟前
大模型输出的“隐性结构塌缩”问题及对策
前端·后端
这儿有一堆花28 分钟前
前端三件套真的落后了吗?揭开现代 Web 开发的底层逻辑
前端·javascript·css·html5
.Cnn1 小时前
JavaScript 前端基础笔记(网页交互核心)
前端·javascript·笔记·交互
醉酒的李白、1 小时前
Vue3 组件通信本质:Props 下发,Emits 回传
前端·javascript·vue.js
anOnion1 小时前
构建无障碍组件之Window Splitter Pattern
前端·html·交互设计
NotFound4862 小时前
实战分享Python爬虫,如何实现高效解析 Web of Science 文献数据并导出 CSV
前端·爬虫·python
徐小夕2 小时前
PDF无限制预览!Jit-Viewer V1.5.0开源文档预览神器正式发布
前端·vue.js·github
WangJunXiang62 小时前
Haproxy搭建Web群集
前端
吴声子夜歌2 小时前
Vue.js——自定义指令
前端·vue.js·flutter
小芝麻咿呀3 小时前
vue--面试题第一部分
前端·javascript·vue.js