简体   繁体   English

创建HTML5画布图案并用它们填充内容

[英]Creating HTML5 canvas patterns and filling stuff with them

I'm having difficulties with .createPattern(image,"repeat") . 我在使用.createPattern(image,"repeat")遇到了困难。

  1. Can I fill a square with my own pattern created by .toDataURL() and .createPattern() ? 我可以使用.toDataURL().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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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