HTML5 Canvas 绘制矩形

在HTML5画布元素上最容易绘制的形状之一是矩形。您可以使用2D上下文函数fillRect()和进行操作strokeRect()。

ini 复制代码
<canvas id="ex1" width="500" height="150" style="border: 1px solid #cccccc;">    
HTML5 Canvas not supported    
</canvas>    
<script>       
var canvas  = document.getElementById("ex1");    
var context = canvas.getContext("2d");    
context.fillStyle = "#ff0000";    
context.fillRect(10,10, 100,100);    
context.strokeStyle = "#0000ff";    
context.strokeRect(30,20, 120,110);      
</script>

行宽 - lineWidth

您可以使用lineWidth2D上下文的属性设置描边矩形的线宽。方法如下:

ini 复制代码
<canvas id="ex4" width="500" height="150" style="border: 1px solid #cccccc;">    
HTML5 Canvas not supported    
</canvas>    
<script>       
var canvas  = document.getElementById("ex4");    
var context = canvas.getContext("2d");    
var x = 10;    
var y = 10;    
var width = 100;    
var height = 100;    
context.lineWidth = 4;    
context.strokeRect(x, y, width, height);      
</script>

矩形颜色

您可以使用 2D上下文的fillStyle或strokeStyle属性设置绘制矩形的颜色。这是第一个示例,这些设置以粗体显示:

ini 复制代码
<canvas id="ex5" width="500" height="150" style="border: 1px solid #cccccc;">    
HTML5 Canvas not supported    
</canvas>    
<script>       
var canvas  = document.getElementById("ex5");    
var context = canvas.getContext("2d");    
context.fillStyle = "#ff0000";    
context.fillRect(10,10, 100,100);    
context.strokeStyle = "#0000ff";    
context.strokeRect(30,20, 120,110);    
</script>

引用

菜鸟教程

相关推荐
六月的可乐几秒前
探索AI在线前端html编辑器IDE
前端·html·ai编程
今禾1 分钟前
深入解析CSS Grid布局:从入门到精通
前端·css·面试
复苏季风3 分钟前
前端接口请求中,GET 和 POST 对于传参的string/number区别
前端·javascript
jump6803 分钟前
从零开始起项目 0.0.
前端
工会代表5 分钟前
前端项目自动化部署改造方案
前端·nginx
Soulkey5 分钟前
Grid布局
前端·css
springfe01018 分钟前
react useCallback应用
前端
毛骗导演11 分钟前
从零构建现代化 CLI 应用:Claude CI 技术实现详解
前端·javascript
CUGGZ13 分钟前
前端开发的物理外挂来了,爽到飞起!
前端·后端·程序员
console.log('npc')26 分钟前
前端性能优化,给录音播放的列表加个播放按键,点击之后再播放录音。减少页面的渲染录音文件数量过多导致加载缓慢
前端·javascript·vue.js·算法