canvas drawImage方法不显示图片的解决方案
先复习一下用法:
context.drawImage(img,sx,sy,swidth,sheight,x,y,width,height);
各个参数说明:
| 参数 | 描述 |
|---|---|
| img | 规定要使用的图像、画布或视频。 |
| sx | 可选。开始剪切的 x 坐标位置。 |
| sy | 可选。开始剪切的 y 坐标位置。 |
| swidth | 可选。被剪切图像的宽度。 |
| sheight | 可选。被剪切图像的高度。 |
| x | 在画布上放置图像的 x 坐标位置。 |
| y | 在画布上放置图像的 y 坐标位置。 |
| width | 可选。要使用的图像的宽度。(伸展或缩小图像) |
| height | 可选。要使用的图像的高度。(伸展或缩小图像) |
用一张图来说明:
context.drawImage(img, sx, sy, sw, sh, dx, dy, dw, dh)
img |
Source image object | Sprite sheet |
sx |
Source x | Frame index times frame width |
sy |
Source y | 0 |
sw |
Source width | Frame width |
sh |
Source height | Frame height |
dx |
Destination x | 0 |
dy |
Destination y | 0 |
dw |
Destination width | Frame width |
dh |
Destination height | Frame height |
以下是w3school给的例子:
var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); var img = document.getElementById("tulip"); ctx.drawImage(img,10,10);
然而实际在运行中图片是不显示的,这是比较坑的问题,解决方法是将drawImage放入
img.onload或者window.onload中。
参考链接:
https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage

浙公网安备 33010602011771号