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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM