报错了Failed to fetch model list: TypeError: Cannot read properties of undefined (reading 'canvas')
at get view (pixi__js.js?v=3e1cf41d:6417:26)
at PreView.vue:85:26
at chunk-CLTUMBBG.js?v=3e1cf41d:4860:40
at callWithErrorHandling (chunk-CLTUMBBG.js?v=3e1cf41d:2295:19)
at callWithAsyncErrorHandling (chunk-CLTUMBBG.js?v=3e1cf41d:2302:17)
at hook.__weh.hook.__weh (chunk-CLTUMBBG.js?v=3e1cf41d:4840:19)
at flushPostFlushCbs (chunk-CLTUMBBG.js?v=3e1cf41d:2481:28)
at flushJobs (chunk-CLTUMBBG.js?v=3e1cf41d:2523:5)
The error message you're encountering:
code
Failed to fetch model list: TypeError: Cannot read properties of undefined (reading 'canvas')
at get view (pixi__js.js?v=3e1cf41d:6417:26)
at PreView.vue:85:26
...
indicates that somewhere in your code, an attempt is being made to access the canvas property of an undefined object. Given the context of your Vue component, this is likely related to the integration with Pixi.js. Let's walk through potential causes and solutions to resolve this issue.
Potential Issue: The canvas ref might not be correctly assigned when you attempt to append the Pixi.js canvas.
Solution:
Verify the Ref Binding: Ensure that the ref="canvas" is correctly bound to the <div class="root"> and that this element exists in the DOM when onMounted is called.
Add Debugging Logs:
Before appending the Pixi.js view, add a console log to verify that canvas.value is not null:
Potential Issue: The Builder object is not imported or defined anywhere in your script, leading to Builder being undefined. Attempting to call Builder.builder_init on an undefined object will throw an error.
Solution:
Import the Builder Object:
Ensure that the Builder object is properly imported at the top of your script. For example:
typescript
import Builder from '../path/to/builder' // Adjust the path accordingly
If Builder is part of a library or another module, make sure it's correctly referenced.
Verify the Builder Implementation:
Ensure that Builder has a builder_init method that returns a promise. For example:
Your Pixi.js setup looks generally correct, but let's ensure all steps are properly handled.
Potential Issues & Solutions:
Canvas Dimensions: You're setting the canvas width and height based on window.screen.width and window.screen.height. In some cases, relying on window.innerWidth and window.innerHeight might be more appropriate, especially if dealing with responsive designs.
typescript
let width = window.innerWidth
let height = window.innerHeight
App Destruction Timing: You're calling app.destroy() immediately after Builder.builder_init. Make sure that you intend to destroy the Pixi.js application at this point. If not, this might lead to unexpected behavior.
typescript
Builder.builder_init(container).then((value) => {
console.log('加载完成')
// Only destroy the app if it's no longer needed
// app.destroy()
})
Error Handling in Pixi.js Initialization: Surround your Pixi.js initialization code with additional try-catch blocks or error handling to catch any Pixi-specific errors.
4. Verify Asset Imports
You have the following imports:
typescript
import liuxinPath from '../assets/liuxin/liuxin.png'
import liuxinPathJS from '../assets/liuxin/liuxin.json'
Potential Issue: If these assets are not correctly imported or if the paths are incorrect, Pixi.js might fail to load them, leading to errors.
Solution:
Check the Asset Paths: Ensure that the paths to liuxin.png and liuxin.json are correct relative to your component file.
Verify Asset Loading: Add logs to confirm that the assets are being loaded correctly.
Handle Asset Loading Errors: Implement error handling when parsing the spritesheet.
typescript
const liuxinsheet = new Spritesheet(
PIXI.Texture.from(liuxinPath),
liuxinPathJS
)
liuxinsheet.parse(() => {
// Success callback
const liuxinsp = new AnimatedSprite(
liuxinsheet.animations['9c0d85519fc29bd805102e958f2e83e5_wps图片']
)
// ... rest of the Pixi.js setup
}, (error) => {
// Error callback
console.error('Failed to parse spritesheet:', error)
})
5. General Debugging Tips
Isolate the Issue: Temporarily remove parts of the onMounted hook to identify which section is causing the error. For example, start by initializing Pixi.js without fetching the model list, then add components back one by one.
Use Vue DevTools: Utilize Vue DevTools to inspect the state of your components and verify that reactive properties are being correctly set.
Check Browser Console: Sometimes, additional errors or warnings in the console can provide more context about what's going wrong.
6. Revised onMounted Hook Example
Here's an example of how you might revise your onMounted hook with added error handling and logging:
typescript
onMounted(async () => {
try {
// Screen dimensions
let width = window.innerWidth
let height = window.innerHeight
console.log('Screen dimensions:', width, height)
console.log(width > height ? '横屏' : '竖屏')
// Initialize Pixi.js Application
let app = new PIXI.Application({
width: width,
height: height,
antialias: true,
backgroundColor: 0x2980b9,
backgroundAlpha: 0.2,
resolution: 1,
})
let canvasInfo = app.view
console.log('Pixi.js Application initialized:', app)
// Parse Spritesheet
const liuxinsheet = new Spritesheet(
PIXI.Texture.from(liuxinPath),
liuxinPathJS
)
liuxinsheet.parse((error) => {
if (error) {
console.error('Error parsing spritesheet:', error)
return
}
const liuxinsp = new AnimatedSprite(
liuxinsheet.animations['9c0d85519fc29bd805102e958f2e83e5_wps图片']
)
liuxinsp.animationSpeed = 0.03
liuxinsp.width = 300
liuxinsp.height = 300
liuxinsp.loop = true
liuxinsp.gotoAndPlay(0)
const container = new PIXI.Container()
container.x = app.screen.width / 2
container.y = app.screen.height / 3
liuxinsp.anchor.set(0.5)
container.addChild(liuxinsp)
app.stage.addChild(container)
// Initialize Builder
if (Builder && typeof Builder.builder_init === 'function') {
Builder.builder_init(container).then(() => {
console.log('Builder loaded successfully')
// Optionally destroy the app if needed
// app.destroy()
}).catch((builderError) => {
console.error('Error initializing Builder:', builderError)
})
} else {
console.error('Builder is not defined or builder_init is not a function')
}
})
// Append Pixi.js canvas to the DOM
if (canvas.value) {
canvas.value.appendChild(canvasInfo)
console.log('Pixi.js canvas appended to DOM')
} else {
console.error('Canvas ref is undefined')
}
// Fetch model list
const httpdata = await Pixihttp.get_model_list()
for (let entry of httpdata.data) {
if (entry.model_category === 'stable_diffusion_xl') {
stable_diffusion_xls.push(entry)
} else if (entry.model_category === 'flux') {
fluxs.push(entry)
}
}
// Sort models by api_calls in descending order
stable_diffusion_xls.sort((a, b) => b.api_calls - a.api_calls)
fluxs.sort((a, b) => b.api_calls - a.api_calls)
console.log('Stable Diffusion XL Models:', stable_diffusion_xls)
console.log('Flux Models:', fluxs)
// Initialize gallery images
for (let i = 1; i <= 100; i++) {
images.push('https://cdn.pixabay.com/photo/2023/08/11/08/29/highland-cattle-8183107_1280.jpg')
}
} catch (error) {
console.error('Failed to fetch model list:', error)
}
})
7. Final Checklist
Import All Necessary Modules: Ensure all modules like Builder are correctly imported.
Verify Asset Paths: Check that all asset paths (images, JSON files) are correct and the assets exist.
Test Pixi.js Initialization Separately: Try initializing Pixi.js without integrating it with other parts of your component to isolate the issue.
Check for Typos: Ensure there are no typos in property names or method calls.
Update Dependencies: Make sure that all your dependencies (Vue, Pixi.js, etc.) are up-to-date and compatible.
8. Alternative Approach: Using ref with Specific Element Types
To make the canvas ref more type-safe and clear, you can specify it as an HTMLDivElement instead of a generic Node:
typescript
const canvas = ref<HTMLDivElement | null>(null)
This provides better type checking and IntelliSense support.
9. Conclusion
The error you're encountering is most likely due to the canvas ref not being correctly assigned or the Builder object being undefined. By following the steps above, you should be able to identify and resolve the issue. Start by adding detailed logging to verify each part of the onMounted hook and ensure that all dependencies and references are correctly set up.
If after these steps the issue persists, please provide more details about the Builder object or any additional related code, and I'll be happy to assist further.