程序運行截圖如下:
源碼如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<canvas id="canvas" style="border:1px solid #aaa;display:block;margin:50px auto;">
當前瀏覽器不支持Canvas,請更換瀏覽器後再試
</canvas>
<script>
window.onload = function() {
let canvas = document.getElementById("canvas");
canvas.width = 800;
canvas.height = 800;
let context = canvas.getContext("2d");
drawRect(context, 100, 100, 400, 400, 10, "#508", "red");
drawFillRect(context, 200, 200, 400, 400, 10, "#508", "blue");
drawFillRect(context, 300, 300, 400, 400, 10, "#508", "rgba(255, 255, 0, 0.5)")
}
function drawRect(cxt, x, y, width, height, borderWidth, borderColor, fillColor){
cxt.beginPath();
cxt.rect(x, y, width, height);
cxt.closePath();
cxt.lineWidth = borderWidth;
cxt.fillStyle = fillColor;
cxt.strokeStyle = borderColor;
cxt.fill();
cxt.stroke();
}
function drawFillRect(cxt, x, y, width, height, borderWidth, borderColor, fillColor){
cxt.lineWidth = borderWidth;
cxt.fillStyle = fillColor;
cxt.strokeStyle = borderColor;
cxt.fillRect(x, y, width, height);
cxt.strokeRect(x, y, width, height);
}
</script>
</body>
</html>
畫矩形有兩種:
一種是:使用
rect()函數畫出框,然後使用:
cxt.lineWidth = borderWidth;
cxt.fillStyle = fillColor;
cxt.strokeStyle = borderColor;
cxt.fill();
這些進行填充。
第二種是使用:
function drawFillRect(cxt, x, y, width, height, borderWidth, borderColor, fillColor){
cxt.lineWidth = borderWidth;
cxt.fillStyle = fillColor;
cxt.strokeStyle = borderColor;
cxt.fillRect(x, y, width, height);
cxt.strokeRect(x, y, width, height);
}
這種方式進行繪製。
關於透明相關的:
cxt.fillStyle = fillColor;
可以通過傳入rgba(255, 255, 0, 0.5)這種方式設置透明度。