canvas + angular

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)`

// 有角度的平移,先旋转,再平移,再旋转回去

参考:

 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》

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值