Skip to content

Canvas 图像

要在 canvas 上绘制图像,主要使用 drawImage() 方法。此方法有多种形式,允许进行图像的绘制、缩放和裁剪。

基本语法如下:

  • drawImage(image, dx, dy): 在坐标 (dx, dy) 处绘制 image。
  • drawImage(image, dx, dy, dWidth, dHeight): 在 (dx, dy) 处绘制 image,并缩放到 dWidth 和 dHeight。
  • drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight): 从源图像坐标 (sx, sy) 处裁剪尺寸为 (sWidth, sHeight) 的区域,然后绘制到 canvas 上的 (dx, dy) 处,并缩放到 dWidth 和 dHeight。

至关重要的是,图像必须完全加载后才能在 canvas 上绘制。尝试绘制未加载的图像通常会导致没有任何内容被绘制或出现错误。

以下是正确加载和绘制图像的方法:

async function drawMyImage() {
const canvas = document.getElementById('myCanvas');
if (!canvas.getContext) {
console.error('Canvas not supported!');
return;
}
const ctx = canvas.getContext('2d');
// Option 1: Using an existing <img> element
// const imgElement = document.getElementById('myImageElement');
// if (imgElement.complete) { // 检查图像是否已加载(例如通过浏览器缓存)
// ctx.drawImage(imgElement, 10, 10);
// } else {
// imgElement.onload = () => { // 设置加载完成后的回调
// ctx.drawImage(imgElement, 10, 10, 150, 100); // 缩放绘制
// };
// imgElement.onerror = () => { // 设置加载错误的回调
// console.error('Error loading image from <img> tag.'); // 从 <img> 标签加载图像错误
// };
// }
// Option 2: Creating an Image object in JavaScript (Recommended for dynamic loading)
// 选项 2:在 JavaScript 中创建 Image 对象(推荐用于动态加载)
const img = new Image();
img.onload = () => {
// Image is loaded, now we can draw it
// 图像已加载,现在可以绘制它了
ctx.drawImage(img, 10, 10); // Draw at original size // 按原始尺寸绘制
// Example: Draw scaled image
// 示例:绘制缩放后的图像
// ctx.drawImage(img, 10, 120, 200, 150);
// Example: Draw a slice of the image
// 示例:绘制图像的一部分(切片)
// ctx.drawImage(img, 0, 0, 50, 50, 10, 280, 100, 100); // (源X, 源Y, 源宽度, 源高度, 目标X, 目标Y, 目标宽度, 目标高度)
};
img.onerror = () => {
console.error('Error loading the image via JavaScript.'); // 通过 JavaScript 加载图像错误
};
img.src = 'your-image.png'; // Replace with your image path. Ensure the image is accessible.
// 设置图像源路径。替换为你的图像路径。确保图像可访问。
}
// Call the function, perhaps after the DOM is fully loaded
// 调用此函数,最好在 DOM 完全加载后
document.addEventListener('DOMContentLoaded', drawMyImage);
// HTML structure for this example:
// 此例的 HTML 结构:
// <canvas id="myCanvas" width="400" height="400" style="border:1px solid #000;"></canvas>
// <!-- If using Option 1, include an img tag -->
// <!-- 如果使用选项 1,包含一个 img 标签 -->
// <!-- <img id="myImageElement" src="your-image.png" alt="My Image" style="display:none;"> -->
  • 我们获取 canvas 元素及其 2D 渲染上下文。
  • 我们创建一个新的 Image 对象。
  • 我们设置一个 onload 事件处理程序。当图像成功加载后,会调用此函数。所有使用此图像的绘制操作都应在此处理程序内部或由其调用。
  • 我们设置一个 onerror 事件处理程序以捕获任何加载错误。
  • 最后,我们设置 Image 对象的 src 属性。这将启动图像加载过程。
  • 如果需要确保图像完全解码并准备就绪(尤其是在性能关键的应用中),使用 async/await 配合 image.decode() 是一种更现代的处理图像加载的方式:await img.decode(); ctx.drawImage(img, 10, 10);(这应该在 async 函数内部,并且通常包含在针对 src 赋值和 decode 调用的 try-catch 块中)。

常见陷阱:过早绘制。如果在 onload 事件触发之前(或在 <img> 标签内容加载之前)调用 drawImage(),图像数据尚未可用,因此不会绘制任何内容。

应用场景:在基于 canvas 的应用中显示用户头像、游戏精灵图、电商网站的产品图片或背景图像。