创建HTML5画布模式并用它们填充内容 [英] Creating HTML5 canvas patterns and filling stuff with them

查看:142
本文介绍了创建HTML5画布模式并用它们填充内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 .createPattern(image,repeat)有困难。

1。我可以用自己的 .toDataURL() .createPattern()? >

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

1. Can I fill a square with my own pattern created by .toDataURL() and .createPattern()?

2。我可以用方格填充正方形,这是当前的画布吗?

2. Can I fill a square with pattern, which is the current canvas?

my jsFiddle

<canvas id="canvas" width="320" height="240" style="border: solid darkblue 1px;background-color: aliceblue"></canvas>



JavaScript



JavaScript

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();`


推荐答案

您将需要为模式创建一个单独的画布,因为您不能自行引用画布来使用模式。

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.

修改的小提琴

Modified fiddle

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();

这篇关于创建HTML5画布模式并用它们填充内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆