So what happens is my clear_one and clear_two functions do not work I checked the error with chrome dev tools and it throws an error:
'ctx' is not defined
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>
Please help me out
The reason nothing is happening is because:
Global scope and function scope. In js, there is the concept of scope. Any variable declared in a function will not work outside of it. Eg
function yay(){
var text = 'I love js!'
}
yay()
console.log(text)
will not work as the variable text is in function scope, but
var text = 'I like js!'
function yay(){
text = 'I love js!'
}
console.log(text)
will work as text is in global scope, and will output I love js
Here is a working fiddle
I think your problem is a simple error because the context. Your variables ctx
and ctx_two
starting and end on function scope;
I suggest you declare your variables out your functions (is not the best approach, but with the time, you can get better ways)
A link about variables and yours scopes:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.