clip.vue 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. <template>
  2. <div>
  3. <canvas :id="id" width="800" height="400" tabindex="0"/>
  4. </div>
  5. </template>
  6. <script lang="ts">
  7. import { Component, Prop, Vue } from "vue-property-decorator";
  8. import { v1 as uuid } from "uuid";
  9. import {SCanvasView, SPainter, SPath, SColor} from "@persagy-web/draw/lib";
  10. class ClipView extends SCanvasView{
  11. img: CanvasImageSource;
  12. _url: string = '';
  13. arcX = 100;
  14. arcY = 100;
  15. stepX = 6;
  16. stepY = 8;
  17. timer: any;
  18. set url(v:string){
  19. if (this._url == v) {
  20. return;
  21. }
  22. this._url = v;
  23. // @ts-ignore
  24. this.img.src = v;
  25. }
  26. get url():string{
  27. return this._url;
  28. }
  29. isLoadOver: boolean = false;
  30. constructor(id:string){
  31. super(id);
  32. this.img = new Image();
  33. this.img.onload = (e) => {
  34. this.isLoadOver = true;
  35. this.update();
  36. };
  37. this.img.onerror = (e) => {
  38. this.isLoadOver = false;
  39. this.update();
  40. console.log("加载图片错误!", e);
  41. };
  42. }
  43. onDraw(painter: SPainter): void {
  44. // @ts-ignore
  45. painter.engine._canvas.save();
  46. // painter.save();
  47. painter.clearRect(0,0,800,400);
  48. clearTimeout(this.timer);
  49. painter.pen.color = SColor.Black;
  50. painter.brush.color = SColor.Black;
  51. painter.drawRect(0, 0, 800, 400);
  52. painter.brush.color = SColor.Transparent;
  53. let path = new SPath();
  54. path.arc(this.arcX, this.arcY, 100, 0, Math.PI*2, 1);
  55. painter.clip = path;
  56. painter.drawPath(path);
  57. // console.log('------->');
  58. if (this.isLoadOver) {
  59. painter.drawImage(this.img, 0, 0, 800, 400);
  60. }
  61. // painter.restore();
  62. // @ts-ignore
  63. painter.engine._canvas.restore();
  64. this.timer = setTimeout(()=>{
  65. if (this.arcX + 100 >= 800) {
  66. this.stepX *= -1;
  67. }
  68. if (this.arcX - 100 < 0) {
  69. this.stepX *= -1;
  70. }
  71. if (this.arcY + 100 >= 400) {
  72. this.stepY *= -1;
  73. }
  74. if (this.arcY - 100 < 0) {
  75. this.stepY *= -1;
  76. }
  77. this.arcX += this.stepX;
  78. this.arcY += this.stepY;
  79. this.update()
  80. }, 17);
  81. }
  82. }
  83. @Component
  84. export default class SelectContainerCanvas extends Vue {
  85. id: string = uuid();
  86. view: ClipView | undefined;
  87. img = require('../../public/assets/img/2.jpg');
  88. mounted(): void {
  89. this.init();
  90. };
  91. init():void{
  92. this.view = new ClipView(this.id);
  93. this.view.url= this.img;
  94. };
  95. beforeDestroy(): void {
  96. clearTimeout(this.view!!.timer);
  97. }
  98. }
  99. </script>