Style và Màu với HTML5 Canvas
HTML5 canvas cung cấp hai thuộc tính quan trọng để áp dụng màu cho một hình:
| STT | Phương thức và Miêu tả |
|---|---|
| 1 | fillStyle Thuộc tính này biểu diễn màu hoặc phong cách để sử dụng bên trong shape |
| 2 | strokeStyle Thuộc tính này biểu diễn màu hoặc phong cách để sử dụng cho các đường xung quanh shape. |
Theo mặc định, màu stroke và fill được thiết lập là màu đen với giá trị màu CSS là #000000.
Ví dụ fillStyle
Sau đây là ví dụ đơn giản sử dụng thuộc tính fillStyle để tạo một mẫu đẹp:
<!DOCTYPE HTML>
<html>
<head>
<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 onload="drawShape();">
<canvas id="mycanvas"></canvas>
</body>
</html>
Ví dụ trên sẽ cho kết quả sau:
Ví dụ strokeStyle
Sau đây là ví dụ đơn giản sử dụng thuộc tính strokeStyle để tạo một mẫu đẹp khác:
<!DOCTYPE HTML>
<html>
<head>
<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 onload="drawShape();">
<canvas id="mycanvas"></canvas>
</body>
</html>
Ví dụ trên sẽ cho kết quả sau:
Công cụ giáo viên (2048.VN)
Tạo- trộn đề thi miễn phí từ file PDF, Word, Giao bài nhanh chóng, Hoàn toàn Free
Bài học HTML5 phổ biến khác tại vietjack.com:
Dành cho bạn
Công cụ giáo viên
- Tạo đề online từ PDF / Word
- Trộn nhiều mã đề, in Offline
- Giao bài online, Quản lí lớp học

