3 回答

TA貢獻1876條經驗 獲得超7個贊
即使函數dessiner()
和ghost.onload()
被多次調用,您的變量x
和y
也只被分配了一次隨機值,因為它們是在全局范圍內定義的。
因此,每次單擊時都會生成圖像,但是......每次都在相同的位置。
解決該問題的一種方法是在您的 中分配 X 和 Y 值ghost.onload()
,或者32 +(Math.random() * (400-64))
直接將其用作drawImage()
函數的參數。

TA貢獻1864條經驗 獲得超2個贊
代碼的編寫方式存在一些問題。
變量ghost沒有被一個preceededlet或var取得了ghost一個全局變量。這意味著您第一次單擊 時dessiner,ghost該函數被調用,但在該函數中 ghost 被重新分配給一個圖像,然后所有進一步調用圖像的嘗試都失敗了。這在您的瀏覽器控制臺中將在第二次點擊后顯示錯誤Uncaught TypeError: ghost is not a function,這可以通過在聲明之前簡單地添加一個“讓”來解決ghost
function ghost() {
let ghost = new Image();
ghost.src = "ghost.png";
ghost.onload = function(){
contexte.drawImage(image,x,y,20,20)
};
}
此后不會再有錯誤,但您仍然會遇到單擊按鈕時圖像數量不會增加的事實。實際上,圖像正在生成,但它被放置在最后一張圖像的正上方,給人一種什么都沒有改變的錯覺。這是因為每次生成新圖像時,您的x和y值都是相同的。這可以通過移動你的創作是固定的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)
};
}
此時,如果您停下來,每次單擊后,圖像都會出現在隨機位置,但舊圖像仍將保留。如果您確實想擺脫舊圖像,您所做的就是在繪制新圖像之前清除畫布。
function dessiner() {
contexte.clearRect(0, 0, canvas.width, canvas.height);
ghost();
}
就這樣你就完成了!

TA貢獻1785條經驗 獲得超8個贊
這應該對你有用。
首先:你在函數 ghost() 中有一個變量 ghost,所以當函數第一次運行時,ghost 變量被設置,因此函數 ghost() 不再作為函數有效,所以將 var ghost 更改為 var ghos 其次:你需要清除在函數 ghost() 中重繪畫布之前,再次獲取變量 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();
}
添加回答
舉報