JavaScript报错:Cannot read property 'show' of undefined 求代码排查
Fixing "Cannot read property 'show' of undefined" in Your Canvas Code
Hey there! Let's walk through the issues in your code that are causing that error, and fix them step by step.
Main Issues Identified
- Missing
BlobClass Definition: The core error happens because you’re trying to create aBlobobject, but there’s no class or constructor function defined for it. When you later try to callblob.show(),blobis undefined—hence the "Cannot read property 'show' of undefined" message. - Incorrect
setIntervalUsage: You wrotesetInterval(draw(), 1000/30)which immediately runs thedrawfunction once, instead of passing the function reference to be called repeatedly. It should besetInterval(draw, 1000/30)(no parentheses afterdraw). - Incomplete
drawFunction: Yourdrawcode is cut off (ctx.rect(0, 0, width, height...), so it doesn’t finish clearing the canvas or rendering the blob. - Implicit Global Variables: Variables like
c,ctx,width, andheightare declared withoutlet/const, making them global scope which can lead to unexpected behavior.
Corrected Code
Here’s the fixed version with all issues addressed:
let blob; const blobs = []; let width = 300; let height = 300; let c, ctx; // Define the Blob class with a show method to draw the circle class Blob { constructor(x, y, radius) { this.x = x; this.y = y; this.radius = radius; } show() { ctx.beginPath(); ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2); ctx.fillStyle = '#2ecc71'; // Green fill for the blob ctx.fill(); ctx.closePath(); } } window.onload = function(){ // Create and configure the canvas element c = document.createElement('canvas'); c.width = width; c.height = height; ctx = c.getContext('2d'); document.body.appendChild(c); // Initialize the blob and start the animation loop blob = new Blob(width/2, height/2, 64); setInterval(draw, 1000/30); // Pass function reference, not execute immediately } function draw(){ // Clear the canvas every frame to prevent overlapping drawings ctx.fillStyle = '#ecf0f1'; // Light gray background ctx.fillRect(0, 0, width, height); // Draw the blob blob.show(); }
Key Fixes Explained
- Added
BlobClass: The class includes a constructor to set the blob’s position and radius, plus ashowmethod that usesctx.arc()to draw the circle. - Fixed
setInterval: Changeddraw()todrawso the function is called repeatedly at 30 FPS, creating a smooth animation. - Completed
drawFunction: Added code to clear the canvas each frame and callblob.show()to render the circle properly. - Proper Variable Declarations: Used
letandconstto avoid implicit global variables, making the code cleaner and less prone to bugs.
When you run this corrected code, you’ll see a green circle centered on a light gray canvas, updating smoothly each frame.
内容的提问来源于stack exchange,提问作者Richard Santos
相关产品推荐
相关产品推荐

