canvas + angular

canvas和svg的选择:canvas比较耗性能

// Canvas状态存储在栈中,每当save()方法被调用后,当前的状态就被推送到栈中保存。

// 每一次调用 restore 方法,上一个保存的状态就从栈中弹出,所有设定都恢复。

// 因此你应该用load事件来保证不会在加载完毕之前使用这个图片

// @ViewChild("myCanvas", { static: true }) 设置为true,在mng-OnInt里,和其它的视图不同

// 我们可以用脚本创建一个新的 HTMLImageElement 对象。要实现这个方法,我们可以使用很方便的Image()构造函数。当脚本执行后,图片开始装载。

// 使用drawImage 将源图对象渲染到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;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 canvasthis.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)`// 有角度的平移,先旋转,再平移,再旋转回去

参考:

 https://medium.com/angular-in-depth/how-to-get-started-with-canvas-animations-in-angular-2f797257e5b4

《How to get started with Canvas animations in Angular》


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部