简体   繁体   中英

Creating HTML5 canvas patterns and filling stuff with them

I'm having difficulties with .createPattern(image,"repeat") .

  1. Can I fill a square with my own pattern created by .toDataURL() and .createPattern() ?
  2. Can I fill a square with a pattern, which is the current canvas?

 var canvas = document.getElementById("canvas"); var context = canvas.getContext("2d"); context.strokeRect(0.5, 0.5, 10, 10); context.arc(5.5, 5.5, 3, 0, Math.PI); context.rect(3, 3, 1, 1); context.rect(7, 3, 1, 1); context.stroke(); var img = new Image(); img.src = canvas.toDataURL(); context.drawImage(img, 10, 10); // works context.beginPath(); var pattern = context.createPattern(img, "repeat"); // doesn't work context.fillStyle = pattern; context.fillRect(20, 20, 100, 100); context.fill(); context.beginPath(); var pattern2 = context.createPattern(canvas, "repeat"); // doesn't work context.fillStyle = pattern2; context.fillRect(120, 20, 100, 100); context.fill(); 
 <canvas id="canvas" width="320" height="240" style="border: solid darkblue 1px;background-color: aliceblue"></canvas> 

You will need to create a separate canvas for the pattern as you cannot self-reference the canvas for use with patterns.

The reason is that when you reference the original canvas you are trying to draw to, the pattern will have the same size and will only draw one instance as there is no room for more than that.

So to make it work you need to define a pattern of a smaller size, hence we need a separate canvas or image and pass that in as a source for the pattern.

 var canvas = document.getElementById("canvas"); var context = canvas.getContext("2d"); // create the off-screen canvas var canvasPattern = document.createElement("canvas"); canvasPattern.width = 10; canvasPattern.height = 10; var contextPattern = canvasPattern.getContext("2d"); // draw pattern to off-screen context contextPattern.beginPath(); contextPattern.strokeRect(0.5, 0.5, 10, 10); contextPattern.arc(5.5, 5.5, 3, 0, Math.PI); contextPattern.rect(3, 3, 1, 1); contextPattern.rect(7, 3, 1, 1); contextPattern.stroke(); // now pattern will work with canvas element var pattern = context.createPattern(canvasPattern,"repeat"); context.fillStyle = pattern; context.fillRect(20, 20, 100, 100); context.fill(); 
 <canvas id="canvas" width="320" height="240" style="border: solid darkblue 1px;background-color: aliceblue"></canvas> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM