2

I would like to set dynamically a color and pattern to a shape using html5 canvas. The pattern is a .png image. When I research the topic I found that you can not mix fillStyle = pattern and fillStyle = color The canvas shape will get only one of them. I would like to have a color in the background and image pattern in the forward dynamically. That is possible?

any idea will be appreciate.enter image description here

andre
  • 192
  • 2
  • 12

1 Answers1

3

Just draw the circular path twice:

  • First time with the solid lime fill

  • Second time with the pattern

Example code and a Demo:

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
setCanvas(canvas, ctx, 300, 300);

var img = new Image();
img.onload = start;
img.src = "https://i.stack.imgur.com/uKmeL.png";

function start() {
  ctx.beginPath();
  ctx.arc(150, 150, 130, 0, Math.PI * 2);
  ctx.closePath();
  ctx.fillStyle = "lime";
  ctx.fill();

  var pattern = ctx.createPattern(img, "repeat");
  ctx.fillStyle = pattern;
  ctx.fill();
}

// https://stackoverflow.com/questions/8696631/canvas-drawings-like-lines-are-blurry/59143499#59143499
function setCanvas(canvas, ctx, w, h) {
  canvas.style.width = w + "px";
  canvas.style.height = h + "px";
  const scale = window.devicePixelRatio;
  canvas.width = w * scale;
  canvas.height = h * scale;
  ctx.scale(scale, scale );
}
body {
  background-color: ivory;
}
canvas {
  border: 1px solid red;
}
<canvas id="canvas"></canvas>

Golden Star

rofrol
  • 14,438
  • 7
  • 79
  • 77
markE
  • 102,905
  • 11
  • 164
  • 176