3 回答

TA貢獻(xiàn)1876條經(jīng)驗(yàn) 獲得超7個(gè)贊
即使函數(shù)dessiner()
和ghost.onload()
被多次調(diào)用,您的變量x
和y
也只被分配了一次隨機(jī)值,因?yàn)樗鼈兪窃谌址秶鷥?nèi)定義的。
因此,每次單擊時(shí)都會(huì)生成圖像,但是......每次都在相同的位置。
解決該問(wèn)題的一種方法是在您的 中分配 X 和 Y 值ghost.onload()
,或者32 +(Math.random() * (400-64))
直接將其用作drawImage()
函數(shù)的參數(shù)。

TA貢獻(xiàn)1864條經(jīng)驗(yàn) 獲得超2個(gè)贊
代碼的編寫(xiě)方式存在一些問(wèn)題。
變量ghost沒(méi)有被一個(gè)preceededlet或var取得了ghost一個(gè)全局變量。這意味著您第一次單擊 時(shí)dessiner,ghost該函數(shù)被調(diào)用,但在該函數(shù)中 ghost 被重新分配給一個(gè)圖像,然后所有進(jìn)一步調(diào)用圖像的嘗試都失敗了。這在您的瀏覽器控制臺(tái)中將在第二次點(diǎn)擊后顯示錯(cuò)誤Uncaught TypeError: ghost is not a function,這可以通過(guò)在聲明之前簡(jiǎn)單地添加一個(gè)“讓”來(lái)解決ghost
function ghost() {
let ghost = new Image();
ghost.src = "ghost.png";
ghost.onload = function(){
contexte.drawImage(image,x,y,20,20)
};
}
此后不會(huì)再有錯(cuò)誤,但您仍然會(huì)遇到單擊按鈕時(shí)圖像數(shù)量不會(huì)增加的事實(shí)。實(shí)際上,圖像正在生成,但它被放置在最后一張圖像的正上方,給人一種什么都沒(méi)有改變的錯(cuò)覺(jué)。這是因?yàn)槊看紊尚聢D像時(shí),您的x和y值都是相同的。這可以通過(guò)移動(dòng)你的創(chuàng)作是固定的x,并y在這樣的的onload功能,擺脫其他聲明的x,并y
function ghost() {
let ghost = new Image();
ghost.src = "ghost.png";
ghost.onload = function(){
let x = 32 +(Math.random() * (400-64));
let y = 32 +(Math.random() * (400-64));
contexte.drawImage(image,x,y,20,20)
};
}
此時(shí),如果您停下來(lái),每次單擊后,圖像都會(huì)出現(xiàn)在隨機(jī)位置,但舊圖像仍將保留。如果您確實(shí)想擺脫舊圖像,您所做的就是在繪制新圖像之前清除畫(huà)布。
function dessiner() {
contexte.clearRect(0, 0, canvas.width, canvas.height);
ghost();
}
就這樣你就完成了!

TA貢獻(xiàn)1785條經(jīng)驗(yàn) 獲得超8個(gè)贊
這應(yīng)該對(duì)你有用。
首先:你在函數(shù) ghost() 中有一個(gè)變量 ghost,所以當(dāng)函數(shù)第一次運(yùn)行時(shí),ghost 變量被設(shè)置,因此函數(shù) ghost() 不再作為函數(shù)有效,所以將 var ghost 更改為 var ghos 其次:你需要清除在函數(shù) ghost() 中重繪畫(huà)布之前,再次獲取變量 x 和 y
var canvas = document.getElementById("canvas");
var contexte = canvas.getContext("2d");
function ghost(){
var x = 32 +(Math.random() * (400-64));
var y = 32 +(Math.random() * (400-64));
ghos= new Image();
ghos.src = "icon.png";
ghos.onload = function(){
// Store the current transformation matrix of canvas
contexte.save();
// Use the identity matrix while clearing the canvas
contexte.setTransform(1, 0, 0, 1, 0, 0);
contexte.clearRect(0, 0, canvas.width, canvas.height);
// Restore the transform
contexte.restore();
contexte.drawImage(ghos,x,y,20,20)
canvas.rem
}};
function dessiner(){
ghost();
}
添加回答
舉報(bào)