The 'Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(CSSImageValue or HTMLCanvasElement or HTMLImageElement or HTMLVideoElement or ImageBitmap or OffscreenCanvas or SVGImageElement or VideoFrame)' error occurs when you pass an incorrect argument type to the drawImage method of a canvas context object.

The drawImage method only accepts the following types as its first argument:

  • CSSImageValue
  • HTMLCanvasElement
  • HTMLImageElement
  • HTMLVideoElement
  • ImageBitmap
  • OffscreenCanvas
  • SVGImageElement
  • VideoFrame

To fix this error, ensure the value you are passing to drawImage is one of these supported types.

For instance, you might be trying to pass a string representing the image URL directly to drawImage. Instead, create a new HTMLImageElement, set its src attribute to the image URL, and then pass this image element to drawImage after it has loaded.

Here's an example:

const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
const img = new Image();

img.onload = () => {
  ctx.drawImage(img, 0, 0);
};

img.src = 'path/to/your/image.jpg'; 

This code snippet first gets references to the canvas element and its 2D rendering context. It then creates a new HTMLImageElement, sets its onload event handler to draw the image onto the canvas once it's fully loaded, and finally sets the image source.

By ensuring you are using the correct types with drawImage, you can avoid this common JavaScript error when working with the Canvas API.

Uncaught TypeError: drawImage on CanvasRenderingContext2D - Invalid Value Type

原文地址: https://www.cveoy.top/t/topic/fTBP 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录