html:canvas画布绘图简单入门-2
【摘要】
canvas示例系列:
html:canvas画布绘图简单入门-1html:canvas画布绘图简单入门-2html:canvas画布绘图简单入门-绘制时钟-3html:canvas画布绘图简单入门-刮...
canvas示例系列:
分辨率和元素尺寸
<canvas
width="600"
height="700"
style="width:800px; height:900px">
</canvas>
- 1
- 2
- 3
- 4
- 5
内容分辨率: 600 * 700
元素尺寸: 800 * 900
示例6:将元素截取后返回画布
像素操作
getImageData()
createImageData()
putImageData()
<canvas id="canvas"
width="600"
height="600"></canvas>
<script>
let canvas = document.querySelector('#canvas');
let ctx = canvas.getContext('2d');
ctx.fillStyle = "red";
ctx.fillRect(0, 0, 50, 50);
let imageData = ctx.getImageData(0, 0, 50, 50);
console.log(imageData);
// 转换元素的颜色数组 RGBA [红色, 绿色, 蓝色, alpha通道]
// [255, 0, 0, 255] => [0, 255, 255, 255]
for (let i = 0; i< imageData.data.length; i += 4) {
imageData.data[i] = 255 - imageData.data[i];
imageData.data[i + 1] = 255 - imageData.data[i + 1];
imageData.data[i + 2] = 255 - imageData.data[i + 2];
imageData.data[i + 3] = 255;
}
console.log(imageData);
ctx.putImageData(imageData, 100, 0);
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
示例7:移动坐标原点
画布坐标原点左上角(0,0)
<canvas id="canvas"
width="600"
height="600"></canvas>
<script>
let canvas = document.querySelector('#canvas');
let ctx = canvas.getContext('2d');
ctx.fillStyle = "red";
ctx.fillRect(0, 0, 50, 50);
// 移动原点坐标(0, 0) => (100, 0)
ctx.translate(100, 0);
ctx.fillStyle = "green";
ctx.fillRect(0, 0, 50, 50);
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
示例8:旋转坐标轴
<canvas id="canvas"
width="600"
height="600"></canvas>
<script>
let canvas = document.querySelector('#canvas');
let ctx = canvas.getContext('2d');
// 将坐标轴顺时针旋转45角
ctx.rotate(Math.PI / 180 * 45);
ctx.fillStyle = "red";
ctx.fillRect(25, -25, 50, 50);
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
示例9:缩放坐标轴
<canvas id="canvas"
width="600"
height="600"></canvas>
<script>
let canvas = document.querySelector('#canvas');
let ctx = canvas.getContext('2d');
ctx.fillStyle = "red";
ctx.fillRect(0, 0, 50, 50);
// 保存画笔状态
ctx.save()
// 坐标轴x, y都放大两倍
ctx.scale(2, 2);
ctx.fillStyle = "green";
ctx.fillRect(50, 0, 50, 50);
// 恢复画笔状态
ctx.restore()
ctx.fillRect(250, 0, 50, 50);
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
文章来源: pengshiyu.blog.csdn.net,作者:彭世瑜,版权归原作者所有,如需转载,请联系作者。
原文链接:pengshiyu.blog.csdn.net/article/details/122263249
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)