要将自定义变换矩阵应用于HTML5 Canvas,我们可以使用transform()方法。 根据以下惯例,此方法需要3 x 3矩阵的六个组件:
html代码:
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="578" height="200"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var rectWidth = 150;
var rectHeight = 75;
// translation matrix:
// 1 0 tx
// 0 1 ty
// 0 0 1
var tx = canvas.width / 2;
var ty = canvas.height / 2;
// apply custom transform
context.transform(1, 0, 0, 1, tx, ty);
context.fillStyle = 'blue';
context.fillRect(rectWidth / -2, rectHeight / -2, rectWidth, rectHeight);
</script>
</body>
</html>