[英]How do I push random images from an array onto a canvas using ctx.drawImage?
我想要一個畫布,每次刷新窗口時都會隨機顯示不同的動物頭。 因此,我試圖將一個隨機圖像從我的頭部陣列推送到我的畫布上。 正如你在下面看到的,這是我的數組。
var heads = ['animals/dog.svg', 'animals/fish.svg', 'animals/monkey.svg'];`
這是我希望數組隨機推送圖像的繪制圖像函數:
ctx.drawImage(img, 60, 50);
這是我的整個上下文代碼:
var heads = ['animals/dog.svg', 'animals/fish.svg', 'animals/monkey.svg'];
function gethead() {
var number = Math.floor(Math.random()*heads.length);
document.write('<img src="'+heads[number]+'" />');}
window.onload = function () {
var img = new Image();
img.src = 'dog.svg';
img.onload = function () {
// CREATE CANVAS CONTEXT.
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.drawImage(img, 60, 50);
// DRAW THE IMAGE TO THE CANVAS.
}
}
誰能解釋我如何使這項工作?
創建一個 img 元素並將 src 設置為 head[generatednumber] 並將其附加到 body。
var img=document.createElement('img');
img.src=heads[number];
document.body.append(img);
使用與圖像相同的變量img
,為 onload 回調編寫一個函數
img.onload = function () { }
並在 drawImage 中傳遞保存圖像引用的變量,即img
document.getElementById('canvas').getContext('2d').drawImage(img, 0,0);
嘗試運行此代碼段
var heads = ['https://cdn.pixabay.com/photo/2015/02/04/08/03/baby-623417__340.jpg', 'https://cdn.pixabay.com/photo/2018/03/11/20/42/mammals-3218028__340.jpg', 'https://cdn.pixabay.com/photo/2016/04/14/08/40/newborn-1328454__340.jpg']; window.onload = function () { let number = Math.floor(Math.random()*heads.length); var img=document.createElement('img'); img.src=heads[number]; document.body.append(img); img.onload = function () { document.getElementById('canvas').getContext('2d').drawImage(img, 0,0); //remove the image after drawing img.style.display="none" } }
<canvas id="canvas"></canvas>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.