HTML5 Canvas填充两种颜色 [英] HTML5 Canvas Fill with two colours

查看:1081
本文介绍了HTML5 Canvas填充两种颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要求用两种颜色填充形状 - 就像棋盘一样。

I have a requirement to fill a shape with a two colours - like a chess board.

我看过css的一些渐变效果但是没有看到任何例子像这样。

I have seen some gradient effects with css but have not seen any examples like this.

这在Html5 Canvas中是否可行?

Would this even be possible in Html5 Canvas?

推荐答案

你确定可以。事实上,你可以使用任何可重复的东西填充任意形状,即使是你在Canvas中制作的形状!

You sure can. In fact you can fill any arbitrary shape with any repeatable thing, even with shapes that you make in the Canvas itself!

这是一个任意形状填充的例子豌豆荚在画布上定义: http://jsfiddle.net/NdUcv/

Here's an example of an arbitrary shape getting filled with "pea pods" that were defined on a canvas: http://jsfiddle.net/NdUcv/

这里有一个简单的棋盘图案: http:// jsfiddle。 net / NdUcv / 2 /

Here it is with a simple checkerboard pattern: http://jsfiddle.net/NdUcv/2/

第二个使形状填充看起来像这样:

That second one makes a shape fill look like this:

我创建了这种模式通过制作画布,然后绘制我想要重复的内容:

I create that pattern by making a canvas and then drawing whatever I want to repeat on it:

var pattern = document.createElement('canvas');
pattern.width = 40;
pattern.height = 40;
var pctx = pattern.getContext('2d');

// Two green rects make a checkered square: two green, two transparent (white)
pctx.fillStyle = "rgb(188, 222, 178)";
pctx.fillRect(0,0,20,20);
pctx.fillRect(20,20,20,20);

然后在我的普通画布上我可以这样做:

Then on my normal canvas I can do:

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

并使用该模式绘制任何内容。

and draw fill anything with that pattern.

当然它不必是画布路径,你可以使用棋盘图像(或任何类型的图像)并使用画布图案用它填充形状。

Of course it doesn't have to be a canvas path, you could use a checkerboard image (or any kind of image) and fill a shape with it using the canvas patterns.

这篇关于HTML5 Canvas填充两种颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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