Search code examples
javascriptcanvasdata-uri

How to set a fill style (texture) to an existing data URI in canvas


I have an existing PNG data URI like:

let dataURI = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAMAQMAAABsu86kAAAABlBMVEUAAAD+qAB849H0AAAAAXRSTlMAQObYZgAAAAxJREFUCNdjSEsgiACnWAlJEDYe/gAAAABJRU5ErkJggg==";

I want to use that as a texture in my canvas that I am doing some draw operations on. I've tried a few things with canvas.fillStyle, but I'm not seeing that working. Colors work fine.

What would be the way to use a dataURI as a texture in drawing operations?


Solution

  • You need to load it as an image first (be sure to handle the asynchronous aspect), so basically to set an image as pattern:

    var img = new Image;
    img.onload = imageIsReady;
    img.src = "data: ....."; // full uri here
    
    function imageIsReady() {
      var pattern = ctx.createPattern(img, "repeat");
      ctx.fillStyle = pattern;
      // fill, etc.
    }