Skip to content Skip to sidebar Skip to footer

Html5 Canvas Fill With Two Colours

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 b

Solution 1:

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.

Solution 2:

I did a quick example

<html><head><hea><bodyonload='xx()'><canvasid='mycanvas'width='256'height='256'>ops</canvas></body><scripttype='text/javascript'>functionxx(){
var canvas= document.getElementById('mycanvas');
    ctx= canvas.getContext('2d');

for(var i=0;i<8;i++){
    for(var j=0;j<8;j++){

if (ctx.fillStyle == '#000000')
ctx.fillStyle = 'blue';
else    ctx.fillStyle = '#000000';


ctx.fillRect(32*j, 32*i, 32,32);
    }
if (ctx.fillStyle == '#000000')
ctx.fillStyle = 'blue';
else    ctx.fillStyle = '#000000';
}

}

Post a Comment for "Html5 Canvas Fill With Two Colours"