程序运行截图如下:
源码如下:
- <!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("https://cdn.jxasp.com:9143/image/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)这种方式设置透明度。