Masking shapes in HTML5 canvas?

后端 未结 2 520
情歌与酒
情歌与酒 2020-12-28 23:17

Apologies if this has been asked elsewhere but it\'s pretty hard to phrase as it is so I couldn\'t find anything.

Is there any way to implement masks in canv

2条回答
  •  一向
    一向 (楼主)
    2020-12-28 23:38

    You just need to create a clipping path and draw your shape in there. The Mozilla Developer Network is a great starting place for learning canvas. Here's the section on clipping.

    I've created a basic fiddle with an example of what I think you are trying to create.

    var ctx = document.getElementById('canvas').getContext('2d');
    ctx.fillRect(0, 0, 150, 150);
    
    // create a clipping path
    ctx.beginPath();
    ctx.moveTo(20, 20);
    ctx.lineTo(20, 130);
    ctx.lineTo(130, 130);
    ctx.lineTo(130, 20);
    ctx.clip();
    
    // backgroud in clipped area
    ctx.fillStyle = "#11c";
    ctx.fillRect(0, 0, 150, 150);
    
    // draw shapes inside clipped area
    ctx.translate(75, 90);
    
    ctx.fillStyle = '#f00';
    
    ctx.fillRect(-15, -40, 40, 40);
    ctx.fillRect(0, 0, 10, 10);
    ctx.fillRect(-25, 10, 60, 60);
    

    Hope this helps, good luck with your project!

提交回复
热议问题