ObjectUtils.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import { Scene } from '../core/Scene'
  2. import { Matrix3 } from '../math/Matrix3'
  3. import { Vector2 } from '../math/Vector2'
  4. import { Object2D } from './Object2D'
  5. /* 基于矩阵创建路径 */
  6. function crtPathByMatrix(
  7. ctx: CanvasRenderingContext2D,
  8. vertices: number[],
  9. matrix: Matrix3,
  10. closePath = false
  11. ) {
  12. const p0 = new Vector2(vertices[0], vertices[1]).applyMatrix3(matrix)
  13. ctx.moveTo(p0.x, p0.y)
  14. // console.log(p0)
  15. for (let i = 2, len = vertices.length; i < len; i += 2) {
  16. const pn = new Vector2(vertices[i], vertices[i + 1]).applyMatrix3(matrix)
  17. ctx.lineTo(pn.x, pn.y)
  18. }
  19. closePath && ctx.closePath()
  20. }
  21. /* 创建路径 */
  22. function crtPath(
  23. ctx: CanvasRenderingContext2D,
  24. vertices: number[],
  25. closePath = false
  26. ) {
  27. const p0 = new Vector2(vertices[0], vertices[1])
  28. ctx.moveTo(p0.x, p0.y)
  29. for (let i = 2, len = vertices.length; i < len; i += 2) {
  30. const pn = new Vector2(vertices[i], vertices[i + 1])
  31. ctx.lineTo(pn.x, pn.y)
  32. }
  33. closePath && ctx.closePath()
  34. }
  35. /* 加载图像的Promise对象 */
  36. function ImagePromise(image: HTMLImageElement) {
  37. return new Promise<HTMLImageElement>((resolve) => {
  38. image.onload = () => {
  39. resolve(image)
  40. }
  41. })
  42. }
  43. /* 图像的批量加载 */
  44. function ImagePromises(images: HTMLImageElement[]) {
  45. return images.map((image) => ImagePromise(image))
  46. }
  47. /* 选择图案 */
  48. function SelectObj(scene: Scene) {
  49. return function (objGroup: Object2D[], mp: Vector2): Object2D | null {
  50. for (let obj of [...objGroup].reverse()) {
  51. if (scene.isPointInObj(obj, mp, obj.pvmMatrix)) {
  52. return obj
  53. }
  54. }
  55. return null
  56. }
  57. }
  58. export { crtPath, crtPathByMatrix, ImagePromise, ImagePromises, SelectObj }