如何使用canvas实现状态保存和变换操作?

摘要:save()和restore() save() 保存当前状态,将当前canvas的状态存入栈中。 restore() 恢复之前save的一个状态,将之前的状态从栈中弹出。 保存的当前状态包含以下信息: 变换(平移、旋转、缩放) 属性: st
save()和restore() save() 保存当前状态,将当前canvas的状态存入栈中。 restore() 恢复之前save的一个状态,将之前的状态从栈中弹出。 保存的当前状态包含以下信息: 变换(平移、旋转、缩放) 属性: strokeStyle, fillStyle, globalAlpha, lineWidth, lineCap, lineJoin, miterLimit, lineDashOffset, shadowOffsetX, shadowOffsetY, shadowBlur, shadowColor, globalCompositeOperation, font, textAlign, textBaseline, direction, imageSmoothingEnabled 剪裁路径 save()和restore()的用处就是有时候用canvas绘图会经过很多操作,然后可以用restore()直接恢复原先的状态,而不用再变换到原来的状态。这个API在需要进行很多变换的时候特别有用。 比如说在一开始先用save()保存了canvas最先的状态,也就是没经过任何操作的状态,然后开始用canvas绘图API绘图,中间对strokeStyle、lineWidth、globalAlpha等很多属性进行了修改,还进行了平移、旋转等等变换操作,这时,如果又要重新再画某个图形,而画这个图形要变换回原来最先的状态才方便画,那么直接restore()变回最初保存的状态就行,否则,又要重新平移、旋转,对各种属性赋值,才变回需要的状态,会非常麻烦。而save()和restore()两行就解决了这个问题。 例子 function draw() { var ctx = document.getElementById('canvas').getContext('2d'); ctx.fillRect(0, 0, 150, 150); // Draw a rectangle with default settings ctx.save(); // Save the default state ctx.fillStyle = '#09F'; // Make changes to the settings ctx.fillRect(15, 15, 120, 120); // Draw a rectangle with new settings ctx.save(); // Save the current state ctx.fillStyle = '#FFF'; // Make changes to the settings ctx.globalAlpha = 0.5; ctx.fillRect(30, 30, 90, 90); // Draw a rectangle with new settings ctx.restore(); // Restore previous state ctx.fillRect(45, 45, 60, 60); // Draw a rectangle with restored settings ctx.restore(); // Restore original state ctx.fillRect(60, 60, 30, 30); // Draw a rectangle with restored settings } 结果 平移 translate(x, y) 将canvas沿x轴平移x个单位,沿y轴平移y个单位。 平移是会移动画布的,是画布的位置变了。
阅读全文