使用画布 2D 加载和渲染图像
创建和加载图片
创建一个新的Image 对象,为src 分配您要加载的图像的URL。然后图像将开始加载。您将无法知道加载图像可能需要多长时间,因此您需要等到图像触发 onload 事件,或者如果您确定资源将始终可用,则仅在其 @987654326 时使用图像@属性是=== true
由于我不知道您的图片资源是否可靠,下面的代码是上述方法的混合,使用 onload 事件标记图片已加载。
var image = new Image(); // a new image object same as <img> tag
image.src = "imageURL"; // the url pointing to the image
image.onload = function(){ this.ready = true; }; // flag image ready
// This will not happen until
// the current code has exited
在画布上绘制图像。
要渲染图像,请使用 2D 上下文函数 drawImage。此函数最多有 9 个参数,其中许多是可选的。详情请见MDN drawImage。
如果您尝试在图像加载之前对其进行渲染,那么您当然不会看到任何东西。如果图像在加载尝试绘制过程中出现错误,则可能会引发错误并停止您的代码运行。因此,请始终确保您的图像已准备好并且可以安全绘制。
从上面的图片加载sn-p下面的sn-p渲染图片
if(image.ready){ // is it ready
ctx.drawImage(image,x,y); // draw image with top left at x,y
}
正在加载许多图像。
每次渲染时检查图像是否准备就绪是低效的。一旦准备好,它总是如此。 This answer 展示了如何加载许多图像。如果您有一个正在进行的动画,而不是在所有图像加载后调用 drawImages 函数,请调用启动动画的函数,或设置一个标志以指示所有图像已加载并且可以安全渲染。
完整的图像渲染功能。
2D API 允许您绘制经过缩放、旋转、淡入/淡出的图像。渲染这样的图像有时被称为精灵(从旧的 16 位时代开始)
函数绘制一个缩放旋转的褪色图像/精灵,并围绕其中心旋转。 x 和 y 是画布上中心所在的位置。 scale 为 1 表示无比例 1 表示较大。 rot 是旋转,0 是没有旋转。 Math.PI 是 180 度。增加的 rot 会顺时针方向旋转,减少的方向会反方向旋转。 alpha 将设置图像的透明度,0 表示不可见,1 表示完全可见。尝试使用 0-1 范围之外的值设置全局 alpha 将不会导致任何变化。下面的代码进行检查以确保 alpha 被钳制。如果你信任 alpha 值,你可以直接设置globalAlpha
function drawSprite(image,x,y,scale,rot,alpha){
ctx.setTransform(scale,0,0,scale,x,y);
ctx.rotate(rot);
ctx.globalAlpha = alpha < 0 ? 0 : alpha > 1 ? 1 : alpha; // if you may have
// alpha values outside
// the normal range
ctx.drawImage(image,-image.width / 2, -image.height / 2);
}
// usage
drawSprite(image,x,y,1,0,1); // draws image without rotation or scale
drawSprite(image,x,y,0.5,Math.PI/2,0.5); // draws image rotated 90 deg
// scaled to half its size
// and semi transparent
该函数保持当前变换和 alpha 不变。如果您在其他地方渲染(不使用此功能),您需要重置 2D 上下文的当前状态。
默认
ctx.setTransform(1,0,0,1,0,0);
ctx.globalAlpha = 1;
要保持当前状态使用
ctx.save();
// draw all the sprites
ctx.restore();