[英]Can someone explain my code why it works?
drawImage()
函數不遵循函數參數來繪制圖像。 笑臉的原始尺寸為213px(寬度)和212px(高度)。 圖像繪制得太大。 繪制圖像的高度為500px,繪制圖像的寬度約為400px(壓縮)。
我更改了下面顯示的代碼。 有用。 圖像將以213x212大小完美地繪制。 但是,我不能使用變量width和height作為實際參數。 即
ctx.drawImage(smiley, sx, sy, swidth, sheight, x, y, width, height);
該圖像將不會繪制! 現在我可以指定任何尺寸,例如
ctx.drawImage(smiley, sx, sy, swidth, sheight, x, y, 500, 500);
尺寸為500x500的圖像可以完美繪制。
我想知道那句話到底是什么
var width = c.setAttribute("width", "500");
呢? 我使用調試器檢查變量寬度,它不包含任何值。 嗯...
如果我刪除語句var width = c.setAttribute("width", "500");
,根本不會繪制圖像!
希望有人可以解釋。
var smiley = new Image(); smiley.src = "images/smiley.jpg"; window.onload = function () { var c = document.getElementById("mypic"); var ctx = c.getContext("2d"); var sx = 0; var sy = 0; var swidth = smiley.width; var sheight = smiley.height; var x = 0; var y = 0; //the following three lines are the original code //and is not working properly. //var width = smiley.width; //var height = smiley.height; //ctx.drawImage(smiley, sx, sy, swidth, sheight, x, y, width, height); //Now, it is working fine var width = c.setAttribute("width", "500"); var height = c.setAttribute("height", "500"); ctx.drawImage(smiley, sx, sy, swidth, sheight, x, y, 213, 212); };
canvas { background-color:green; width: 500px; height: 500px; }
<canvas id="mypic" ></canvas>
這里沒有什么要考慮的:首先是它不是window.onload
,它應該是圖像對象onload。 然后,您可以根據要繪制的圖像的實際大小設置畫布的高度和寬度。 這是它的快速預覽。
var c = document.getElementById('canvas') var ctx = c.getContext('2d') var img = new Image(); img.src = 'https://upload.wikimedia.org/wikipedia/commons/thumb/e/e0/SNice.svg/220px-SNice.svg.png' img.onload = function() { c.width = img.width; c.height = img.height; ctx.drawImage(img, 0, 0, img.width, img.height); };
<canvas id="canvas" ></canvas>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.