Home > Software design >  Use pattern (not img) inside canvas
Use pattern (not img) inside canvas

Time:06-04

When I create visualization inside svg, I can fill a rect using pattern that is defined inside defs

            <defs>
                <pattern id="hash4_4" width="8" height="8" patternUnits="userSpaceOnUse" patternTransform="rotate(45)">
                    <rect width="4" height="8" transform="translate(0,0)" fill="lightgray"></rect>
                </pattern>
            </defs>

I want to use the same pattern inside canvas visualization but can't find a way to do that. I googled it and found method canvas.createPattern() but all examples include inserting there an image, not custom rect pattern as above.

Is it possible to use somehow my own <pattern> inside canvas?

CodePudding user response:

You can use the pattern in an SVG document and draw the SVG as an image on the canvas.

For the example I'm using a data URL.

let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');


let img = new Image();

img.addEventListener('load', e => {
  ctx.drawImage(e.target, 0, 0);
});

img.src = 'data:image/svg xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB2aWV3Qm94PSIwIDAgNDAwIDQwMCIgd2lkdGg9IjQwMCIgaGVpZ2h0PSI0MDAiPgogIDxkZWZzPgogICAgPHBhdHRlcm4gaWQ9Imhhc2g0XzQiIHdpZHRoPSI4IiBoZWlnaHQ9IjgiIHBhdHRlcm5Vbml0cz0idXNlclNwYWNlT25Vc2UiIHBhdHRlcm5UcmFuc2Zvcm09InJvdGF0ZSg0NSkiPgogICAgICA8cmVjdCB3aWR0aD0iNCIgaGVpZ2h0PSI4IiB0cmFuc2Zvcm09InRyYW5zbGF0ZSgwLDApIiBmaWxsPSJsaWdodGdyYXkiPjwvcmVjdD4KICAgIDwvcGF0dGVybj4KICA8L2RlZnM CiAgPHJlY3Qgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgZmlsbD0idXJsKCNoYXNoNF80KSIgLz4KPC9zdmc ';
<p>SVG:<br><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 400 400" width="400" height="400">
  <defs>
    <pattern id="hash4_4" width="8" height="8" patternUnits="userSpaceOnUse" patternTransform="rotate(45)">
      <rect width="4" height="8" transform="translate(0,0)" fill="lightgray"></rect>
    </pattern>
  </defs>
  <rect width="100%" height="100%" fill="url(#hash4_4)" />
</svg></p>

<p>Canvas:</p>
<canvas id="canvas" width="400" height="400"></canvas>

  • Related