我正在创建HTML5画布对象(矩形)并根据文本框中输入的值填充颜色(验证仅输入百分比值)。
我从堆栈溢出
找到了一个链接这是代码
$(document).ready(function() {
$("#my_input").keypress(function(event) {
// Allow only backspace and delete
if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 37) {
$("#myCanvas").animate({ opacity: 0.25 });
}
else {
// Ensure that it is a number and stop the keypress
if (event.keyCode < 48 || event.keyCode > 57) {
event.preventDefault();
}
}
});
});
这是矩形的代码
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
context.beginPath();
context.rect(188, 50, 200, 100);
context.fillStyle = 'yellow';
context.fill();
context.lineWidth = 7;
context.strokeStyle = 'black';
context.stroke();
这是我的HTML代码
Numberic Value <input type ="textbox" id="my_input" class="numeric" name="Enter Value" placeholder="Enter value"/>
<canvas id="myCanvas" width="578" height="200"></canvas>
我究竟想要什么当我在文本框中输入10%的值时,颜色必须仅填充该百分比,直到100%
这里我尝试使用动画不透明度0.25
如果我在文本框中输入任何值,我会得到画布的结果减少0.25%
请帮助我解决这个问题
先谢谢
参考:Fill color
与上面的链接类似,当我在文本框中输入数字
时,我想要解决方案答案 0 :(得分:0)
尝试这样的事情:
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var perc = 0.1;
var maxWidth = 200;
var maxHeight = 100;
$(document).ready(function() {
$("#my_input").keyup(function(event) {
// Allow only backspace and delete
if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 37) {
//$("#myCanvas").animate({ opacity: 0.25 });
}
else {
// Ensure that it is a number and stop the keypress
if (event.keyCode < 48 || event.keyCode > 57) {
event.preventDefault();
}
}
perc = Number.parseInt($("#my_input").val()) / 100 ;
draw();
});
function draw(){
// clear
context.clearRect(0, 0, 1000, 1000);
var x = 188;
var y = 50;
// outline
context.beginPath();
context.rect(x, y, maxWidth, maxHeight);
context.lineWidth = 7;
context.strokeStyle = 'black';
context.stroke();
// fill
context.beginPath();
context.fillStyle = 'yellow';
context.rect(x, y, maxWidth * perc, maxHeight);
context.fill();
}
draw();
});