HTML canvas fillStyle 属性
定义用红色填充的矩形:
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
您的浏览器不支持 HTML5 canvas 标签。</canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "#FF0000";
ctx.fillRect(20, 20, 150, 100);
</script>
浏览器支持
Internet Explorer 9、Firefox、Opera、Chrome 和 Safari 支持 fillStyle 属性。
注意:Internet Explorer 8 及之前的版本不支持 <canvas> 元素。
定义和用法
fillStyle 属性设置或返回用于填充绘画的颜色、渐变或模式。
默认值: | #000000 |
---|---|
JavaScript 语法: | context.fillStyle=color|gradient|pattern; |
属性值
值 | 描述 |
---|---|
color | 指示绘图填充色的 CSS 颜色值。默认值是 #000000。 |
gradient | 用于填充绘图的渐变对象(线性 或 放射性)。 |
pattern | 用于填充绘图的 pattern 对象。 |
更多实例
定义从上到下的渐变,作为矩形的填充样式:
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
您的浏览器不支持 HTML5 canvas 标签。
</canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var my_gradient = ctx.createLinearGradient(0, 0, 0, 170);
my_gradient.addColorStop(0, "black");
my_gradient.addColorStop(1, "white");
ctx.fillStyle = my_gradient;
ctx.fillRect(20, 20, 150, 100);
</script>
定义从左到右的渐变,作为矩形的填充样式:
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
您的浏览器不支持 HTML5 canvas 标签
</canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var my_gradient = ctx.createLinearGradient(0, 0, 170, 0);
my_gradient.addColorStop(0, "black");
my_gradient.addColorStop(1, "white");
ctx.fillStyle = my_gradient;
ctx.fillRect(20, 20, 150, 100);
</script>
定义从黑到红到白的的渐变,作为矩形的填充样式:
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
您的浏览器不支持 HTML5 canvas 标签。
</canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var grd = ctx.createLinearGradient(0, 0, 170, 0);
grd.addColorStop(0, "black");
grd.addColorStop(0.5, "red");
grd.addColorStop(1, "white");
ctx.fillStyle = grd;
ctx.fillRect(20, 20, 150, 100);
</script>
<p>图片应用:</p>
<img src="/examples/img_lamp.jpg" id="lamp">
<p>画布:</p>
<button onclick="draw('repeat')">重复</button>
<button onclick="draw('repeat-x')">重复-x</button>
<button onclick="draw('repeat-y')">重复-y</button>
<button onclick="draw('no-repeat')">不重复</button>
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
您的浏览器不支持 HTML5 canvas 标签。
</canvas>
<script>
function draw(direction) {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.clearRect(0, 0, c.width, c.height);
var img = document.getElementById("lamp")
var pat = ctx.createPattern(img, direction);
ctx.rect(0, 0, 220, 128);
ctx.fillStyle = pat;
ctx.fill();
}
</script>
