款式和颜色(Styles and Colors)
优质
小牛编辑
137浏览
2023-12-01
HTML5画布提供以下两个重要属性来将颜色应用于形状 -
Sr.No. | 方法和描述 |
---|---|
1 | fillStyle 此属性表示要在形状内使用的颜色或样式。 |
2 | strokeStyle 此属性表示用于形状周围线条的颜色或样式。 |
默认情况下,笔触和填充颜色设置为黑色,即CSS颜色值#000000。
fillStyle示例
下面是一个简单的例子,它利用上面提到的fillStyle属性来创建一个漂亮的模式。
<!DOCTYPE HTML>
<html>
<head>
<style>
#test {
width: 100px;
height:100px;
margin: 0px auto;
}
</style>
<script type = "text/javascript">
function drawShape() {
// get the canvas element using the DOM
var canvas = document.getElementById('mycanvas');
// Make sure we don't execute when canvas isn't supported
if (canvas.getContext) {
// use getContext to use the canvas for drawing
var ctx = canvas.getContext('2d');
// Create a pattern
for (var i = 0;i<7;i++) {
for (var j = 0;j<7;j++) {
ctx.fillStyle = 'rgb(' + Math.floor(255-20.5*i)+ ','+
Math.floor(255 - 42.5*j) + ',255)';
ctx.fillRect( j*25, i* 25, 55, 55 );
}
}
} else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
}
}
</script>
</head>
<body id = "test" onload = "drawShape();">
<canvas id = "mycanvas"></canvas>
</body>
</html>
一个strokeStyle示例
下面是一个简单的例子,它利用上面提到的fillStyle属性来创建另一个漂亮的模式。
<!DOCTYPE HTML>
<html>
<head>
<style>
#test {
width: 100px;
height:100px;
margin: 0px auto;
}
</style>
<script type = "text/javascript">
function drawShape() {
// get the canvas element using the DOM
var canvas = document.getElementById('mycanvas');
// Make sure we don't execute when canvas isn't supported
if (canvas.getContext) {
// use getContext to use the canvas for drawing
var ctx = canvas.getContext('2d');
// Create a pattern
for (var i = 0;i<10;i++) {
for (var j = 0;j<10;j++) {
ctx.strokeStyle = 'rgb(255,'+ Math.floor(50-2.5*i)+','+
Math.floor(155 - 22.5 * j ) + ')';
ctx.beginPath();
ctx.arc(1.5+j*25, 1.5 + i*25,10,10,Math.PI*5.5, true);
ctx.stroke();
}
}
} else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
}
}
</script>
</head>
<body id = "test" onload = "drawShape();">
<canvas id = "mycanvas"></canvas>
</body>
</html>