I'm developing a college work that basically consists of creating a kind of "Paint" using canvas
of HTML5 in conjunction with Javascript, but I came across a problem trying to update a canvas
that serves to show the current size of dashboard ...
I am using a input
of type range
to set the dash size and the oninput
event to detect the value change in input
, at the moment, I have the following code:
HTML
<input type="range" id="lineSize" class="no_margin range" value="2" min="1" max="20" />
<canvas id="showSize" width="40" height="40" />
Javascript
var lineSize = document.getElementById("lineSize");
function clearCanvas(canvas) {
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
function updateLineSize(size) {
var canvas = document.getElementById("showSize");
clearCanvas(canvas);
var ctx = canvas.getContext("2d");
ctx.arc(canvas.width/2, canvas.height/2, size/2.0, 0, 2 * Math.PI, false);
ctx.fillStyle = "#000000";
ctx.fill();
}
updateLineSize(lineSize.value);
lineSize.oninput = function() {
updateLineSize(this.value);
}
What happens is that every time the updateLineSize
function is called, it always fills the circle with the largest size
size already used, even after reducing the value in input
.
How could I solve this problem?
----- EDIT -----
I was able to solve the problem by recreating canvas
every time I change the value of input
, changing the updateLineSize
function as follows:
function updateLineSize(size) {
var holder = document.getElementById("showSizeHolder");
while (holder.firstChild) {
holder.removeChild(holder.firstChild);
}
var canvas = document.createElement("canvas");
canvas.id = "showSize";
canvas.className = "option";
holder.appendChild(canvas);
canvas.width = 40;
canvas.height = 40;
var ctx = canvas.getContext("2d");
ctx.arc(canvas.width/2, canvas.height/2, size/2.0, 0, 2 * Math.PI, false);
ctx.fillStyle = "#000000";
ctx.fill();
}
But could anyone explain why it did not work the other way?