canvas和svg的选择:canvas比较耗性能
// Canvas状态存储在栈中,每当save()方法被调用后,当前的状态就被推送到栈中保存。
// 每一次调用 restore 方法,上一个保存的状态就从栈中弹出,所有设定都恢复。
// 因此你应该用load事件来保证不会在加载完毕之前使用这个图片
// @ViewChild("myCanvas", { static: true }) 设置为true,在mng-OnInt里,和其它的视图不同
// 我们可以用脚本创建一个新的 HTMLImageElement 对象。要实现这个方法,我们可以使用很方便的Image()构造函数。当脚本执行后,图片开始装载。
// 使用drawImage 将源图对象渲染到canvas里
<canvas #myCanvas fxLayout="row" height="999" width="999"> </canvas>
export enum MachineType {
//BODY = "assets/machine-demo/machine-body.png", // 不是svg 图片,可控制背景层
BODY = "assets/machine/body.svg", // 不是svg 图片,可控制背景层
TABLE = "assets/machine/table.svg",
PILLAR = "assets/machine/rocket.png"
}
ngOnDestroy(): void {
window.cancelAnimationFrame(this.requestID); // 使得在组件销毁时阻止动画
}
@ViewChild("myCanvas", { static: true })
private readonly myCanvas: ElementRef<HTMLCanvasElement>;
private ctx: CanvasRenderingContext2D;
private readonly body = new Image();
private readonly table = new Image();
private readonly pillar = new Image();
private canvasWidth: number = 10;
private canvasHeight: number = 10;
requestID: number;
image = new Image();
draw() {
// this.ctx.globalCompositeOperation = "source-over"; // 在现有的画布内容后面绘制新的图形
this.ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight); // clear canvas
this.ctx.drawImage(this.body, 0, 0, 999, 999); // 背景
this.ctx.save();
if (this.canvasHeight < 70 && this.canvasHeight > -70) {
this.canvasHeight--;
}
this.ctx.translate(this.canvasWidth, this.canvasHeight);
this.ctx.drawImage(this.pillar, this.canvasWidth, this.canvasHeight); //要移动的物体
this.ctx.restore();
this.requestID = window.requestAnimationFrame(() => this.draw());
console.log(this.canvasHeight, this.canvasWidth);
}
ngOnInit() {
console.log(this.canvasWidth, this.canvasHeight, "233");
this.image.src = "assets/machine-demo/rocket.png";
this.pillar.src = "assets/machine-demo/machine-pillar.svg";
this.body.src = MachineType.BODY;
this.table.src = MachineType.TABLE;
this.ctx = this.myCanvas.nativeElement.getContext("2d");
this.table.onload = () => {
this.ctx.drawImage(this.table, 0, 0);
};
}
transform: `rotate(9deg) translateX(-${this.XAaxisTable}px) rotate(-9deg)`
// 有角度的平移,先旋转,再平移,再旋转回去
参考:
《How to get started with Canvas animations in Angular》