1
I am developing a college job that consists basically in creating a kind of "Paint" using the canvas HTML5 in conjunction with Javascript, but came across a problem when trying to update a canvas which serves to display the current stroke size...
I’m using a input of the kind range to set the stroke size and event oninput to detect the value change in the input, at the moment, I have the code below:
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 function updateLineSizeis called, it always fills the circle with the size of the largest size already used, even after reducing the input.
How could I solve this problem?
----- EDIT -----
I managed to solve the problem by recreating the canvas every time I change the value of input, changing the function updateLineSize 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 someone could explain to me why it doesn’t work the other way?