zoukankan      html  css  js  c++  java
  • HTML5 Canvas实现刮刮卡效果实例

    HTML:

    <style>
    #canvas {
        border: 1px solid blue;
        position: absolute;
        left: 10px;
        top: 10px;
        background:url(../Images/1.jpg) no-repeat center center;
        background-size:contain;
    }
    </style>
    <canvas id="canvas"></canvas>

    一、解决方案1是使用clearRect清空鼠标位置的像素

    var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext('2d');
    ctx.fillStyle = 'gray';
    ctx.rect(0, 0, canvas.width, canvas.height);
    ctx.fill();
    //解决方案1是使用clearRect清空鼠标位置的像素
    var isClear = false;
    //设置清空部分
    canvas.onmousedown = function (ev) {
        isClear = true;
    }
    canvas.onmouseup = function () {
        isClear = false;
    }
    canvas.onmousemove = function (ev) {
        if (isClear == false)
            return;
        ev = ev || window.event;
        //清空像素,根据当前所在点
        var curX = ev.clientX - canvas.offsetLeft;
        var curY = ev.clientY - canvas.offsetTop;
        var step = 20;
        ctx.clearRect(curX - step / 2, curY - step / 2,
            step, step);
        ev.stopPropagation();
    }

    二、解决方案2是使用globalCompositeOperation,重叠处理,重叠的透明处理

    var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext('2d');
    ctx.fillStyle = 'gray';
    ctx.rect(0, 0, canvas.width, canvas.height);
    ctx.fill();
    
    //解决方案2是使用globalCompositeOperation,重叠处理
    //优点使用 fill() 不限制是否是矩形
    //在与源不重叠的区域上保留目标。其他部分都变成透明的。
    ctx.globalCompositeOperation = 'destination-out';
    var isClear = false;
    //设置清空部分
    canvas.onmousedown = function (ev) {
        isClear = true;
    }
    canvas.onmouseup = function () {
        isClear = false;
    }
    canvas.onmousemove = function (ev) {
        if (isClear == false)
            return;
        ev = ev || window.event;
        //清空像素,根据当前所在点
        var curX = ev.clientX - canvas.offsetLeft;
        var curY = ev.clientY - canvas.offsetTop;
        var step = 10;
        ctx.beginPath();
        ctx.arc(curX, curY, step, 0, Math.PI * 2, false);
        ctx.fill();
        ev.stopPropagation();
    }

  • 相关阅读:
    Linux常见故障及修复方法
    2019/作业
    使用net 模式上网的步骤
    2019 年 1
    处理请求数据
    REST 表现层状态转化
    @RequestMapping注解的属性,将请求约束精细化
    SpringMVC 概述
    基于XML文档的声明式事务配置
    事务@Transactional注解的属性
  • 原文地址:https://www.cnblogs.com/tianma3798/p/5897416.html
Copyright © 2011-2022 走看看