0
点赞
收藏
分享

微信扫一扫

html:canvas画布绘图简单入门-2

西红柿上校 2022-03-10 阅读 51


分辨率和元素尺寸

<canvas 
width="600"
height="700"
style="width:800px; height:900px">
</canvas>

内容分辨率: 600 * 700

元素尺寸: 800 * 900

示例6:将元素截取后返回画布

像素操作

getImageData()

createImageData()

putImageData()

html:canvas画布绘图简单入门-2_html

<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>

示例7:移动坐标原点

画布坐标原点左上角(0,0)

html:canvas画布绘图简单入门-2_css3_02

<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>

示例8:旋转坐标轴

html:canvas画布绘图简单入门-2_html_03

<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>

示例9:缩放坐标轴

html:canvas画布绘图简单入门-2_html_04

<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>



举报

相关推荐

0 条评论