In HTML5 canvas, how to mask an image with a background of my choice?

前端 未结 1 868
甜味超标
甜味超标 2021-02-03 10:43

I tried to make this happen with canvas\' globalCompositeOperation, but had no luck so I\'m asking here. There are similar questions here, but I did not find my cas

1条回答
  •  太阳男子
    2021-02-03 11:27

    Here’s how to composite your “roof pattern” on top of your “house” using “roofOverlay”

    enter image description here

    This is a multi-part process:

    1. Draw the house on canvas#1.
    2. Draw the red roofOverlay on canvas#2.
    3. Set canvas#2’s context.globalCompositeOperation = 'source-in'
    4. Draw your desired pattern on canvas#2
    5. Compositing will cause your desired pattern to replace the red overlay—only in the red overlay area.

    Here is a Fiddle that loads grass on your roof: http://jsfiddle.net/m1erickson/SWP6v/

    And here is code that uses a lattice pattern fill on your roof:

    Note: I'm assuming that you want the house and roof on separate canvases so you can flip through a variety of roof choices. If you need everything on 1 canvas, you can just draw the roof canvas onto the house canvas.

    
    
    
     
    
    
    
    
    
    
    
    
    
    

    0 讨论(0)
提交回复
热议问题