canvas涂抹效果

canvas涂抹效果

画布涂抹效果

html和css

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style type="text/css">
        canvas {
            z-index: 100;
            position: absolute;
            left: 0;
            top: 0;
        }
    </style>
</head>

<body>
    <canvas id="canvas" width="500" height="375">
    </canvas>
    <script type="text/javascript" src='erase.js'></script>
    <script type="text/javascript">
        erase('canvas');
    </script>
</body>

</html>

js

var erase = function (id) {
    var canvas = document.getElementById(id);
    var ctx = canvas.getContext('2d');
    var img = new Image();
    img.onload = function () {
        // alert('加载');
        ctx.drawImage(img, 0, 0);
    }
    img.src = "image/a.jpg";
    // 将图片画到canvas
    ctx.drawImage(img, 0, 0);
    var offsetX = canvas.offsetLeft;
    var offsetY = canvas.offsetTop;
    var mousedown = false;

    ctx.rect(0, 0, canvas.width, canvas.height);
    ctx.fill();
    // 在目标图像顶部显示源图像
    ctx.globalCompositeOperation = 'source-atop';

    function eventDown(e) {
        e.preventDefault();
        mousedown = true;
    }

    function eventUp(e) {
        e.preventDefault();
        mousedown = false;
    }

    function eventMove(e) {
        e.preventDefault();
        if (mousedown) {
            if (e.changedTouches) {
                e = e.changedTouches[e.changedTouches.length - 1];
            }
            var x = (e.clientX + document.body.scrollLeft || e.pageX) - offsetX || 0;
            var y = (e.clientY + document.body.scrollTop || e.pageY) - offsetY || 0;
            ctx.beginPath();
            ctx.fillStyle = "white";
            ctx.arc(x, y, 20, 0, Math.PI * 20);
            ctx.fill();
        }
    }

    canvas.addEventListener('touchstart', eventDown);
    canvas.addEventListener('touchend', eventUp);
    canvas.addEventListener('touchmove', eventMove);
    canvas.addEventListener('mousedown', eventDown);
    canvas.addEventListener('mouseup', eventUp);
    canvas.addEventListener('mousemove', eventMove);

}

这篇文章有 52 个评论

  1. abone hilesi

    Arkadaslar bu siteye dün giris yaptim ama 2 3 saat degil benim takipçilerim 12 saat sonra geldi sanirim herkes farkli??

发表评论