LOADING

加载过慢请开启缓存 浏览器默认开启

基于Canvas的效果图生成,多重混合效果

前言

见有些定制类业务,在前端给用户定制时提供的设计器,往往需要生成一张效果图,本文将基于Canvas的混合技术,实现一个简单的效果图生成方案。

效果图生成

准备素材

首先准备好需要的素材:
需要一张白板图,并且将其拆分(至少两张)为定制区域和固定区域。
还需要一张定制图片。

定制区域和固定区域

完整代码如下:

<img src="img/custom.png" alt="" id="custom" style="display: none;">
<img src="img/top.png" alt="" id="top" style="display: none;">
<img src="img/resource.png" alt="" id="resource" style="display: none;">

<canvas id="canvas" width="500" height="500"></canvas>

<script>
    const canvas = document.getElementById('canvas');
    const ctx = canvas.getContext('2d');
    const customImg = document.getElementById('custom');
    const topImg = document.getElementById('top');
    const resourceImg = document.getElementById('resource');

    window.addEventListener('load', function() {
        ctx.clearRect(0, 0, canvas.width, canvas.height); 
        ctx.globalCompositeOperation = 'source-over';

        // 绘制定制图案
        ctx.drawImage(resourceImg, 0, 0, canvas.width, canvas.height);
        ctx.globalCompositeOperation = 'destination-in';
        ctx.drawImage(customImg, 0, 0, canvas.width, canvas.height);

        // 叠加纹理
        ctx.globalCompositeOperation = 'multiply'
        const pattern = ctx.createPattern(customImg, 'repeat');
        ctx.fillStyle = pattern;
        ctx.fillRect(0, 0, canvas.width, canvas.height);

        // 绘制固定图案
        ctx.globalCompositeOperation = 'source-over';
        ctx.drawImage(topImg, 0, 0, canvas.width, canvas.height);

        ctx.globalCompositeOperation = 'source-over';
    })
</script>
  1. 在绘制定制图案时,将globalCompositeOperation设置为destination-in,将定制图案作为遮罩层,将纹理图案作为底色,实现剪贴蒙版效果。保证定制图案不会超出定制区域。
  2. 使用multiply正片叠底混合模式,将customImg创建为可重复的纹理图案, 实现为定制图案添加纹理效果。
  3. 最后,把topImg绘制到画布上,“拼”出完整的效果图。

效果图如下:
效果图

重点就是multiply正片叠底混合模式,为定制图案添加纹理效果,使其看上去更加真实。
没有纹理的效果图如下:
效果图


end