Reputation: 920
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?
Upvotes: 4
Views: 3354
Reputation: 1
You can use ctx.createLinearGradient
with .addColorStop()
to create a gradient. If you add two stops at the same distance, you get a hard split in colors.
<html>
<body>
<canvas id="myCanvas" width="300" height="300" style="border:1px solid grey"></canvas>
<script>
const c = document.getElementById("myCanvas");
const ctx = c.getContext("2d");
// Create Gradient
const grd = ctx.createLinearGradient(0, 0, 200, 0);
grd.addColorStop(0, "black");
grd.addColorStop(0.5, "black");
grd.addColorStop(0.5, "yellow");
grd.addColorStop(1, "yellow");
// Fill Rectangle
ctx.fillStyle = grd;
ctx.fillRect(0, 0, 200, 200);
</script>
</body>
</html>
Upvotes: 0
Reputation: 63872
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:
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.
Upvotes: 9
Reputation: 477
I did a quick example
<html>
<head>
<hea>
<body onload='xx()'>
<canvas id='mycanvas' width='256' height='256'>ops</canvas>
</body>
<script type='text/javascript'>
function xx(){
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';
}
}
Upvotes: 1