[英]Fill a rectangle in html5 canvas depending on a specific value
在我的jsfiddle中,有一個用黃色填充的簡單矩形我需要的是更新DrawRectangle以一種方式填充矩形,具體取決於特定的值(如果我給它100的話),如果15大於矩形寬度的15%,則應填充整個矩形應該只填寫http://jsfiddle.net/J4HuQ/
var val = 100;
DrawRectangle(val);
function DrawRectangle(value){
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
context.beginPath();
context.rect(0,0,200,50);
context.fillStyle = 'yellow';
context.fill();
context.stroke();
}
您需要的是一個簡單的數學比例200:100 = x:15
= (15*200)/100
= 30
Jsfiddle在這里: http : //jsfiddle.net/6nKjN/
這個功能應該可以解決
function fill(percent){
//clear canvas
context.clearRect(0, 0, canvas.width, canvas.height)
context.beginPath();
//change canvas.width to the max width of the rectangle if need be.
context.rect(0,0,Math.round(canvas.width*(percent/100)),50);
context.fillStyle = 'yellow';
context.fill();
context.stroke();
}
這是一個小提琴
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.