html - Javascript - Canvas - overlaying a transparent png on a previousley filled color - Stack Overflow

admin2025-04-21  1

If I draw a rectangle on a canvas, fill it with a solid colour. Is it possible to fill it again with an transparent png, so that I can still see the original colour in the background?

Something like, dummy code -

  ctx.beginPath();
  ctx.lineTo( //draw a rectangle )
  ctx.fillStyle = "#FF0000" 
  ctx.fill();
  var imageObj = new Image();
  function drawPattern() {
       var pattern = ctx.createPattern(imageObj, "repeat");
       ctx.fillStyle = pattern;
       ctx.fill();
  }
  imageObj.onload = drawPattern;
  imageObj.src = "images/dot.png"; //transparent png

I've tried a similar approach and it's not working.

Is there another way of doing this? Am I missing something?

If I draw a rectangle on a canvas, fill it with a solid colour. Is it possible to fill it again with an transparent png, so that I can still see the original colour in the background?

Something like, dummy code -

  ctx.beginPath();
  ctx.lineTo( //draw a rectangle )
  ctx.fillStyle = "#FF0000" 
  ctx.fill();
  var imageObj = new Image();
  function drawPattern() {
       var pattern = ctx.createPattern(imageObj, "repeat");
       ctx.fillStyle = pattern;
       ctx.fill();
  }
  imageObj.onload = drawPattern;
  imageObj.src = "images/dot.png"; //transparent png

I've tried a similar approach and it's not working.

Is there another way of doing this? Am I missing something?

Share Improve this question edited Aug 10, 2011 at 9:24 Finnnn asked Aug 9, 2011 at 15:03 FinnnnFinnnn 3,6006 gold badges49 silver badges69 bronze badges 1
  • It works for me on Chrome. Are you sure it is transparent? – pimvdb Commented Aug 9, 2011 at 15:15
Add a ment  | 

1 Answer 1

Reset to default 4

What you've got will work just fine. Make sure you have a truly transparent PNG.

Here's a working example of your code:

http://jsfiddle/BDXc7/

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745202169a290120.html

最新回复(0)