javascript使用canvas绘制矩形的方法

canvas元素使用JavaScript在网页上绘制图像。画布是一个矩形区域,您可以控制其每一像素。canvas 拥有多种绘制路径、矩形、圆形、字符以及添加图像的方法

绘制之前我们需要先创建一个canvas元素到网页

<canvas id="draw" style="width: 640px; height:480px; border: 1px solid #EEE;"></canvas>

然后我们绘制一个无填充的矩形框,我的javascript代码如下

var cs = document.getElementById("draw");
var ct = cs.getContext("2d");
ct.strokeStyle = "red";
ct.lineWidth = 1;
ct.strokeRect(30,20,45,35);

strokeRect是用来绘制无填充的矩形(X轴起点,Y轴起点,X轴终点,Y轴终点),lineWidth是边框宽度,strokeStye是边框颜色

{5794BC18-9FF9-4474-81F4-3DE14C10969C}_20190609220522.jpg

接下来我们绘制一个填充色彩的矩形框

var cs = document.getElementById("draw");
var ct = cs.getContext("2d");
ct.fillStyle = "gray"
ct.fillRect(30,20,45,35);

跟上面差不多,主要是strokeStye更换为fillRect,然后可以使用fillStyle填充颜色,如果不填充颜色默认就是黑色的

注意使用strokeStye是没有lineWidth的,如果需要边框需要使用strokeStye将fillRect框一遍再加边框

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://sulao.cn/post/687.html

我要评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。