每当一个HTML5画布上绘制形状,有两个属性,你需要设置:
1、Stroke
2、Fill
笔触和填充决定的形状如何绘制。Stroke(笔触)是一个形状的轮廓。Fill(填充)是在形状内部的内容。
下面这图是绘制了一个蓝色外轮廓和绿色填充的矩形(实际上是两个矩形):
下面试实现的代码:
<span style="font-size:14px;">// 1. wait for the page to be fully loaded.
window.onload = function() {
drawExamples();
}
function drawExamples(){
// 2. Obtain a reference to the canvas element.
var canvas = document.getElementById("ex1");
// 3. Obtain a 2D context from the canvas element.
var context = canvas.getContext("2d");
// 4. Draw grahpics.
context.fillStyle = "#009900";
context.fillRect(10,10, 100,100);
context.strokeStyle = "#0000ff";
context.lineWidth = 5;
context.strokeRect(10,10, 100,100);
}</span>
请注意的笔触样式和填充样式是分开设置,使用strokeStyle
和fillStyle
的2D背景的性质。
还得注意这lineWidth属性,这里设置了一个线宽为5,最后,注意在2D背景下是如何指示或者画一个矩形填充或者是矩形轮廓。