美文网首页
canvas-裁切clip()

canvas-裁切clip()

作者: 我只会吃饭 | 来源:发表于2019-07-09 08:15 被阅读0次

    使用图形上下文不带参数的clip()方法来实现Canvas图形裁切功能,该方法会使用先创建好的路径对canvas设置裁剪区域,裁剪指定区域显示内容

    切记:裁剪是对画布进行的,裁剪后的画布是不能恢复到原来的大小,因此使用save及restore

    语法:

    context.clip();

    栗子:

    know.gif
    1. 准备工作: 裁切为圆形,则需要圆心,及每步的长度
    // 起始圆心坐标
    var arcX = 100;
    var arcY = 100;
    // 起始步长
    var stepX = 6;
    var stepY = 8;
    
    1. 画圆
    function draw() {
        // 保存上下文的设置及变换的状态
        ctx.save();
        // 清空画布
        ctx.clearRect(0, 0, 500, 500);
        // 重洗画图
        ctx.fillStyle = 'orange';
        ctx.fillRect(0, 0, 500, 500);
        ctx.fill();
    
        // 设置裁切区域
        ctx.beginPath();
        ctx.fillStyle = '#FFF';
        ctx.arc(arcX, arcY, 100, 0, 2 * Math.PI);
    //先绘制好裁切路径,然后调用clip
        ctx.clip();
        ctx.fill();
    
        ctx.beginPath();
        // 字号 字体加粗   字体
        ctx.font = '40px bold';
        // 字体填充色
        ctx.fillStyle = 'blue';
    
        ctx.fillText('小贝真好', 200, 200);
    
        ctx.strokeStyle = 'black';
    
        ctx.strokeText('小贝是谁', 200, 300);
        // 恢复之前保存的状态
        ctx.restore();
    
    }
    
    1. 来个定时器, 顺便判断一下可运动的范围
    var timer = setInterval (function () {
            // 100 为圆的半径  500为画布的大小
            if (arcX + 100 >= 500) {
                stepX *= -1;
            }
    
            if (arcX - 100 < 0) {
                stepX *= -1;
            }
    
            if (arcY + 100 >= 500) {
                stepY *= -1;
            }
    
            if (arcY - 100 < 0) {
                stepY *= -1;
            }
    
            arcX += stepX;
            arcY += stepY;
            draw();
    
    }, 17);
    

    相关文章

      网友评论

          本文标题:canvas-裁切clip()

          本文链接:https://www.haomeiwen.com/subject/lrbqqctx.html