Html5中的画布操作之矩阵转换操作-transform()和setTransform()

矩阵转换 | transform(a, b, c, d, e, f)
canvas/transform/transform.html

<!DOCTYPE HTML>
<html>
<head>
<title>矩阵转换 | transform(a, b, c, d, e, f)</title>
</head>
<body>
<canvas id="canvas" width="400" height="400" style="background-color: rgb(222, 222, 222)">
您的浏览器不支持 canvas 标签
</canvas>
<br />
<button type="button" onclick="drawIt();">不断地点我看 Demo</button>
<button type="button" onclick="clearIt();">清除画布</button>

<script type="text/javascript">

var ctx = document.getElementById('canvas').getContext('2d');

var canvasScaleX = 1;
var canvasScaleY = 1;

var stepScaleX = 1.1;
var stepScaleY = 1.1;

function drawIt() {
if (canvasScaleX == 1 && canvasScaleY == 1)
ctx.strokeRect(
0, 0, 60, 60);

canvasScaleX
*= stepScaleX;
canvasScaleY
*= stepScaleY;

/*
* context.transform(a, b, c, d, e, f) - 按指定的矩阵转换当前的用户坐标系
* 相当于:context.transform(M11, M12, M21, M22, OffsetX, OffsetY)
*
*
* |X| |M11(默认值 1) M21(默认值 0) 0|
* |Y| = |x y 1| * |M12(默认值 0) M22(默认值 1) 0|
* |1| |OffsetX(默认值 0) OffsetY(默认值 0) 1|
*
* X = x * M11 y * M12 OffsetX
* Y = x * M21 y * M22 OffsetY
*/
ctx.strokeStyle
= "blue";
ctx.transform(stepScaleX,
0, 0, stepScaleY, 0, 0);
ctx.strokeRect(
0, 0, 60, 60);
}

function clearIt() {
ctx.transform(
1 / canvasScaleX, 0, 0, 1 / canvasScaleY, 0, 0);
canvasScaleX
= 1;
canvasScaleY
= 1;
ctx.strokeStyle
= "black";

ctx.clearRect(
0, 0, 400, 400);
}

</script>
</body>
</html>


矩阵转换 | setTransform(a, b, c, d, e, f)
canvas/transform/setTransform.html

<!DOCTYPE HTML>
<html>
<head>
<title>矩阵转换 | setTransform(a, b, c, d, e, f)</title>
</head>
<body>
<canvas id="canvas" width="400" height="400" style="background-color: rgb(222, 222, 222)">
您的浏览器不支持 canvas 标签
</canvas>
<br />
<button type="button" onclick="drawIt();">Demo</button>
<button type="button" onclick="clearIt();">清除画布</button>

<script type="text/javascript">

var ctx = document.getElementById('canvas').getContext('2d');

function drawIt() {
ctx.strokeStyle
= "red";
ctx.scale(
2, 2);
ctx.strokeRect(
0, 0, 60, 60);

/*
* context.setTransform(a, b, c, d, e, f) - 首先重置用户坐标系,然后再按指定的矩阵转换用户坐标系(translate, rotate, scale, transform 是针对当前用户坐标系做转换,而 setTransform 是针对重置后的用户坐标系做转换)
* 相当于:context.setTransform(M11, M12, M21, M22, OffsetX, OffsetY)
*
* 关于仿射矩阵参考:http://www.cnblogs.com/webabcd/archive/2008/11/03/1325150.html
*
* |X| |M11(默认值 1) M21(默认值 0) 0|
* |Y| = |x y 1| * |M12(默认值 0) M22(默认值 1) 0|
* |1| |OffsetX(默认值 0) OffsetY(默认值 0) 1|
*
* X = x * M11 y * M12 OffsetX
* Y = x * M21 y * M22 OffsetY
*/
ctx.strokeStyle
= "blue";
ctx.setTransform(
1, 0, 0, 1, 0, 0);
ctx.strokeRect(
0, 0, 60, 60);
}

function clearIt() {
ctx.clearRect(
0, 0, 400, 400);
}

</script>
</body>
</html>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值