Canvas图片的合成

本文主要探讨HTML5 Canvas中如何进行图像的合成操作,并详细讲解了如何使用裁剪路径来处理图像,为网页增加动态效果和交互体验。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Canvas图片的合成

1. 图片的合成

globalCompositeOperation = type;//设置绘制图形的绘制顺序
    *   type的值为:
    *   1. source-over(默认,新图像会覆盖原有图像)
    *   2. source-in (仅出现新图像与原有图像的重叠部分的新图像,其他区域都变透明)
    *   3. source-out (仅显示新图像未与老图像重叠的部分,其他区域都变透明)
    *   4. source-atop (显示老图像 + 新图像与老图像的重叠部分)
    *   5. destination-over (原有图像覆盖新图像)
    *   6. destination-in   (仅出现原有图像与新图像的重叠部分的原有图像,其他区域变透明)
    *   7. destination-out  (仅出现原有图像未与新图像重叠的部分)
    *   8. destination-atop (新图像 + 原有图像与新图像的重叠部分)
    *   9. lighter (新图像与原有图像的重叠部分做加处理)
    *   10.darken  (新图像与原有图像的重叠部分取RGB每部分的最黑的像素)
    *   11.lighten (新图像与原有图像的重叠部分取RGB每部分的最亮的像素)
    *   12. xor (重叠部分会变成透明)
    *   13. copy (只有新图像会被保留,其余的全部被清除)

2. 裁剪路径

clip() //将已经创建的路径转换为裁剪路径;clip只能作用在改方法调用之后的绘制的图像
<html>
<head>
    <title>Canvas</title>
</head>
<body>
    <canvas id="canvas" width="800" height="600px" style="border: dashed 1px #24d1ec;"></canvas>
    <script>
        function draw() {
            let canvas = document.getElementById('canvas');
            let ctx = canvas.getContext('2d');

            //compositeDraw(ctx);
            clip(ctx)
        }

        function compositeDraw(ctx) {
            ctx.fillStyle="#eeee00";
            ctx.fillRect(0, 0, 200, 200);

            //ctx.globalCompositeOperation="source-over";
            //ctx.globalCompositeOperation = 'source-in';
            //ctx.globalCompositeOperation = 'source-out';
            //ctx.globalCompositeOperation = 'source-atop';
            //ctx.globalCompositeOperation = 'lighter';
            ctx.globalCompositeOperation = 'darken';

            ctx.fillStyle = "#00eeee";
            ctx.fillRect(100, 100, 200, 200);
        }

        function clip(ctx) {
            ctx.beginPath();
            ctx.fillStyle = '#00eeee';
            ctx.fillRect(100, 100, 100, 100);
            ctx.arc(20, 20, 100, 0, Math.PI * 2); //将改路径设置为裁剪路径
            ctx.stroke();

            ctx.clip();

            ctx.fillStyle = 'pink';
            ctx.fillRect(20, 20, 100, 100);
        }

        draw();
    </script>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值