123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117 |
- import {onMounted, ref} from "vue";
- import blueImageUrl from '@/assets/login-rotate-blue.png'
- import yellowImageUrl from '@/assets/login-rotate-yellow.png'
- interface IPoint {
- x: number;
- y: number;
- }
- class CircleItem {
- ctx: CanvasRenderingContext2D
- img: HTMLImageElement
- r: number
- w: number
- h: number
- x: number
- y: number
- speed: number
- rectCenterPoint: IPoint
- cacheCanvas: HTMLCanvasElement
- cacheCtx: CanvasRenderingContext2D
- constructor(ctx: CanvasRenderingContext2D, img: HTMLImageElement, r: number, x: number, y: number, speed: number) {
- this.ctx = ctx
- this.img = img;
- this.r = r;
- this.w = r * 2;
- this.h = r * 2;
- this.x = x;
- this.y = y;
- this.speed = speed;
- this.rectCenterPoint = {
- x: r,
- y: r,
- };
- this.cacheCanvas = document.createElement("canvas")
- this.cacheCtx = this.cacheCanvas.getContext("2d") as CanvasRenderingContext2D
- this.cache();
- }
- draw() {
- this.rotate();
- this.ctx.scale(1, 0.3);
- this.ctx.drawImage(
- this.cacheCanvas,
- 0,
- 0,
- this.w,
- this.h,
- this.x - this.r,
- this.y - this.r,
- this.r * 2,
- this.r * 2
- );
- this.ctx.scale(1, 1 / 0.3);
- }
- cache() {
- this.cacheCanvas.width = this.w;
- this.cacheCanvas.height = this.h;
- this.cacheCtx.save();
- this.cacheCtx.beginPath();
- this.cacheCtx.drawImage(this.img, 0, 0, this.r * 2, this.r * 2);
- this.cacheCtx.closePath();
- this.cacheCtx.restore();
- }
- rotate() {
- this.cacheCtx.clearRect(0, 0, this.w, this.h);
- this.cacheCtx.translate(this.rectCenterPoint.x, this.rectCenterPoint.y);
- this.cacheCtx.rotate((this.speed * Math.PI) / 180);
- this.cacheCtx.translate(-this.rectCenterPoint.x, -this.rectCenterPoint.y);
- this.cacheCtx.drawImage(this.img, 0, 0, this.r * 2, this.r * 2);
- }
- }
- // 旋转底座
- export default function useRotateCanvas() {
- const CANVAS_W = 1800
- const CANVAS_H = 600
- const canvasRef = ref<HTMLCanvasElement>();
- onMounted(() => {
- if (canvasRef.value) {
- const canvas = canvasRef.value
- const ctx = canvas.getContext("2d") as CanvasRenderingContext2D;
- const blueImg = new Image();
- blueImg.src = blueImageUrl;
- let rotateBlue: CircleItem
- blueImg.onload = function () {
- rotateBlue = new CircleItem(ctx, blueImg, 750, CANVAS_W / 2, 800, 1);
- };
- const yellowImg = new Image();
- yellowImg.src = yellowImageUrl;
- let rotateYellow: CircleItem
- yellowImg.onload = function () {
- rotateYellow = new CircleItem(ctx, yellowImg, 400, CANVAS_W / 2, 800, 0.6);
- };
- function animate() {
- ctx.clearRect(0, 0, CANVAS_W, CANVAS_H);
- rotateBlue && rotateBlue.draw();
- rotateYellow && rotateYellow.draw();
- requestAnimationFrame(animate);
- }
- animate();
- }
- })
- return {
- canvasRef
- }
- }
|