在单个状态更改中执行此操作。 ctx 变换矩阵有 6 个部分。 ctx.setTransform(a,b,c,d,e,f); (a,b) 代表 x,y 方向并缩放图像的顶部。 (c,d) 表示 x,y 方向和缩放图像的一侧将沿着。 (e,f) 表示图像将被绘制的 x,y 位置。
默认矩阵(恒等矩阵)是ctx.setTransform(1,0,0,1,0,0)在方向(1,0)上画上边,在方向(0,1)上画边,在x = 0, y = 0处画一切。
减少状态变化可以提高渲染速度。当它只是绘制几张图像时,这并不重要,但是如果您想以每秒 60 帧的速度为游戏绘制 1000 多张图像,则需要最小化状态更改。如果可以,您还应该避免使用保存和恢复。
该函数绘制一个围绕其中心点旋转和缩放的图像,该中心点位于 x,y 处。比例小于 1 会使图像更小,大于 1 会使图像更大。 ang 以弧度表示,0 没有旋转,Math.PI 为 180 度,Math.PI*0.5 Math.PI*1.5 分别为 90 和 270 度。
function drawImage(ctx, img, x, y, scale, ang){
var vx = Math.cos(ang) * scale; // create the vector along the image top
var vy = Math.sin(ang) * scale; //
// this provides us with a,b,c,d parts of the transform
// a = vx, b = vy, c = -vy, and d = vx.
// The vector (c,d) is perpendicular (90deg) to (a,b)
// now work out e and f
var imH = -(img.Height / 2); // get half the image height and width
var imW = -(img.Width / 2);
x += imW * vx + imH * -vy; // add the rotated offset by mutliplying
y += imW * vy + imH * vx; // width by the top vector (vx,vy) and height by
// the side vector (-vy,vx)
// set the transform
ctx.setTransform(vx, vy, -vy, vx, x, y);
// draw the image.
ctx.drawImage(img, 0, 0);
// if needed to restore the ctx state to default but should only
// do this if you don't repeatably call this function.
ctx.setTransform(1, 0, 0, 1, 0, 0); // restores the ctx state back to default
}