45-使用scale实现图形缩放_哔哩哔哩_bilibili45-使用scale实现图形缩放是一次性学会 Canvas 动画绘图(核心精讲+50个案例)2023最新教程的第46集视频,该合集共计53集,视频收藏或关注UP主,及时了解更多相关视频内容。https://www.bilibili.com/video/BV16T411B7kP?spm_id_from=333.788.videopod.episodes&vd_source=9218320e7bcc2e793fa8493559f4acd7&p=46
先使用缩放 .scale() ,再填充内容 ,fillRect() ,关键句:
context.scale(1.3, 1);
context.fillStyle = "red";
context.fillRect(0, 0, 100, 100); // 红色矩形,横向拉伸 1.3 倍
因为没有清空画布,所以最后小绿色正方形会覆在第二个蓝色正方形上面,效果图:
【完整代码】
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>canvas {background-color: #ccc;display: block;margin: auto;}</style>
</head><body>
</body>
<script>const canvas = document.createElement('canvas');canvas.width = 600;canvas.height = 400;document.body.append(canvas);const context = canvas.getContext('2d');// canvas的位移api// 所有的位置变换都是基于原点的变化(左上角)// 在0,0初始位置绘制方形,之后它会根据translate进行100,100的偏移// context.translate(100, 100)// 缩放context.scale(1, 1)context.fillRect(0, 0, 100, 100)// 第一个 timeout(2000ms)setTimeout(function () {context.save();context.scale(1.3, 1);context.fillStyle = "red";context.fillRect(0, 0, 100, 100); // 红色矩形,横向拉伸 1.3 倍context.restore();}, 2000);// 第二个 timeout(3000ms)setTimeout(function () {context.save();context.scale(1.3, 1.5);context.fillStyle = "blue";context.fillRect(0, 0, 100, 100); // 蓝色矩形,横向 1.3 倍,纵向 1.5 倍context.restore();}, 3000);// 第三个 timeout(4000ms)setTimeout(function () {context.save();context.scale(0.5, 0.5);context.fillStyle = "green";context.fillRect(0, 0, 100, 100); // 绿色矩形,缩小到 10x10 像素context.restore();}, 4000);
</script></html>