所以會發生什么是我的 clear_one 和 clear_two 函式不起作用我用 chrome 開發工具檢查了錯誤,它拋出了一個錯誤:
'ctx' 未定義
function Circle_one() {
let canvas = document.getElementById("MyCanvas_one");
const ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(350, 160, radius_one, 0, 2 * Math.PI);
ctx.strokeStyle = "#c3c3c3";
ctx.fillStyle = fillcolor_one;
ctx.stroke();
ctx.fill();
fillcolor = 'red';
}
function Circle_two() {
let canvas = document.getElementById("MyCanvas_two");
const ctx_two = canvas.getContext("2d");
ctx_two.clearRect(0, 0, canvas.width, canvas.height);
ctx_two.beginPath();
ctx_two.arc(350, 160, radius_two, 0, 2 * Math.PI);
ctx_two.strokeStyle = "#c3c3c3";
ctx_two.fillStyle = fillcolor_two;
ctx_two.stroke();
ctx_two.fill();
fillcolor = 'red';
}
//clear--
function clear_one() {
ctx.clearRect(0, 0, canvas.width, canvas.height)
}
function clear_two() {
ctx_two.clearRect(0, 0, canvas.width, canvas.height)
}
<span id="span_clear_one">
<button style="background-color: #e4e1d4;width:70px; height:60px;" name='clear_one' type ="button" onclick= "clear_one()"><img src="https://img.myloview.com/stickers/delete-remove-symbol-garbage-bin-dustbin-icon-delete-symbols-for-perfect-mobile-and-web-ui-design-black-trash-can-icon-isolated-on-white-background-office-trash-icon-vector-illustration-700-198973179.jpg" width="55px"></button>
</span>
<span id="span_clear_two">
<button style="background-color: #e4e1d4;width:70px; height:60px;" name='clear_two' type ="button" onclick= "clear_two()"><img src="https://img.myloview.com/stickers/delete-remove-symbol-garbage-bin-dustbin-icon-delete-symbols-for-perfect-mobile-and-web-ui-design-black-trash-can-icon-isolated-on-white-background-office-trash-icon-vector-illustration-700-198973179.jpg" width="55px"></button>
</span>
請幫幫我
uj5u.com熱心網友回復:
我認為您的問題是一個簡單的錯誤,因為背景關系。您的變數ctx以及ctx_two函式范圍的開始和結束;
我建議您在函式中宣告變數(這不是最好的方法,但隨著時間的推移,您可以獲得更好的方法)
關于變數和您的范圍的鏈接:
uj5u.com熱心網友回復:
什么都沒有發生的原因是:
- 您忘記呼叫函式
- 畫布尚未創建
- 未定義 fillcolor_one、radius_one、fillcolor_two 和 radius_two
- 您不能同時描邊和填充。
- 變數不在全域范圍內。(解釋如下)
全域作用域和函式作用域。在js中,有作用域的概念。在函式中宣告的任何變數都不能在它之外作業。例如
function yay(){
var text = 'I love js!'
}
yay()
console.log(text)
由于變數文本在函式范圍內,因此不起作用,但是
var text = 'I like js!'
function yay(){
text = 'I love js!'
}
console.log(text)
將作為文本在全域范圍內作業,并將輸出I love js
這是一個作業小提琴
提示:使用 var 或 let 宣告變數
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/468534.html
標籤:javascript
