当前位置:网站首页>canvas概述
canvas概述
2022-07-26 18:26:00 【前端小草籽】
目录
canvas概述
1.我们为什么要学canvas?
以前我们用div+css 可以绘制矩形、圆角矩形、圆形、或者椭圆形,可是若想绘制三角形、五角形,或者异形,那就很难了。
因此,这个时候我们就需要使用canvas 绘图。
我们可以使用canvas 绘制复杂图形,做动画,处理图像,开发游戏,处理视频…


这时候,会svg的小伙伴可能会说,用svg也可以绘制上面的形状。
svg与canvas 确实有着很多共通之处,很多项目可以用SVG 开发,也可以用canvas 开发。
但svg与canvas的差异也挺大的:
- svg,是矢量图形,缩放不失真;支持鼠标事件,选择方便;不适合图形数量较大的场景。
- canvas,是位图,缩放失真;鼠标事件只能通过canvas 接收,其内部图形无法接收;适合图像数量较大的场景。
2-canvas 是什么?
- 广义:h5 新增canvas 2d 绘图功能
- 在html 中: canvas 是html 标签,可以理解为一张画布。我们需要用js 在canvas 里绘制图形。
3-如何设置canvas 的尺寸?
设置canvas 的 width、height 属性:
<canvas id="canvas" width="700" height="800">也可用js 设置:
const canvas=document.getElementById('canvas');
canvas.width=300;
canvas.height=150;注:不要使用css 设置canvas 尺寸,除非想要调整图像清晰度。
如果在canvas标签中不写宽高,其会有一个默认宽高300*150.但是如果通过css渲染其宽高500x500,相当于把300x150的图片拉到500x500,拉变形。
canvas 上下文对象
1-canvas 上下文对象是什么?
如果说canvas 是画布,那么canvas 上下文对象就是画笔。

2-如何获取canvas 上下文对象
获取上下文对象的方法:canvas.getContext(‘2d’)
//画布
const canvas=document.getElementById('#canvas');
//画笔
const ctx=canvas.getContext('2d');3-获取了上下文对象后,如何用它画画?
使用画笔在canvas 上画画,要考虑三个方面:
- 颜色
- 形状
- 绘图方法
<canvas id="canvas" width="700" height="800">
不兼容
</canvas>
<script>
//画布
const canvas=document.getElementById('canvas');
//画笔
const ctx=canvas.getContext('2d');
//填充色
ctx.fillStyle='red';
//绘制填充矩形 若不写 ctx.fillStyle='red'; 默认为黑色
ctx.fillRect(20,20,400,200)
</script>
canvas 兼容性
canvas 兼容ie9 及其以上

总结
canvas 绘图的步骤:
1.建立canvas 画布。
2.通过canvas 画布获取上下文对象,也就是画笔。
3.设置画笔(描边颜色strokeStyle)颜色。
4.设置图形形状。
5.绘制图形。
边栏推荐
- Usage scenarios for automated testing
- Some time series modeling strategies (I)
- conda转移项目虚拟环境必备技能+pip速度下载太慢解决办法
- Mathematical basis of deep learning
- ReentrantLock学习之---基础方法
- 聊聊如何用 Redis 实现分布式锁?
- 彻底关闭win10自动更新
- Synchronized theory
- 第九章 实用建模技术
- How to write the test case of mobile app? What are the mobile app test points?
猜你喜欢

这22个绘图(可视化)方法很重要,值得收藏!
![[C language implementation] - dynamic / file / static address book](/img/5a/655d9a4799b3e874a454a183dee3f1.png)
[C language implementation] - dynamic / file / static address book

Image preview embedding location of blog maintenance record

C # create and read dat file cases

B站SRE负责人亲述 713事故后的多活容灾建设|TakinTalks大咖分享

用低代码搭建千人食品制造企业高效管理系统案例分析

香港高防IP优势及哪些行业适合使用

线性代数第3章向量

指标和标签是做什么的

Still using xshell? You are out. I recommend a more modern terminal connection tool
随机推荐
AttributeError: ‘Upsample‘ object has no attribute ‘recompute_ scale_ factor‘
Pads draw 2.54mm row needle
如果密钥忘记,多个设备分别不同的密钥,云端是如何同步
C#获取本地时间/系统时间
LeetCode-138-复制带随机指针的链表
服务发现原理分析与源码解读
指标和标签是做什么的
【YOLOv5】--详细版训练自己的数据集 保姆级学习日志记录 手把手教程
Introduce the difference between @getmapping and @postmapping in detail
If the key is forgotten and multiple devices have different keys, how does the cloud synchronize
配置服务器环境
EN 1504-7混凝土结构保护和修理用产品钢筋防腐—CE认证
Network protocol: tcp/ip protocol
文件深度监控策略
Mongodb stats counts the space occupied by the collection
[刷题] 二分答案求解
Software process that testers must know
【C语言实现】----动态/文件/静态通讯录
测试人员必须知道的软件流程
线性代数第4章线性方程组