BBaysinger BBaysinger - 6 months ago 61
Javascript Question

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

I have an existing PNG data URI like:


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
, 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?

Answer Source

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.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download