Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 Canvas Fill with two colours

Tags:

html

css

canvas

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

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

Would this even be possible in Html5 Canvas?

like image 359
sianabanana Avatar asked Nov 02 '25 14:11

sianabanana


1 Answers

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!

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

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

That second one makes a shape fill look like this:

enter image description here

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.

like image 72
Simon Sarris Avatar answered Nov 04 '25 07:11

Simon Sarris