[英]Problems with canvas html5 can't close a draw
我正在開發一個網站,你可以插入人的數據,每個人用圖像(圓圈)表示,圖像在html表中(行是年份,列是月份),取決於出生約會,他們將處於一個位置或其他位置。 嗯,我必須將圖像與畫布鏈接起來制作一個數字,一個近似的數字。 到目前為止,我只是設法用線條加入它,我知道如果你使用屬性".fill()"
這個數字將被關閉,但它不起作用,我不知道為什么。 我做錯了什么?
這是我的js代碼:(每次插入一個人時,我在html的按鈕中調用onClick()事件中的函數“person”)
function position(year, mon) //this function puts the images
{
$('#' + year + ' .' + mon).prepend('<img class="black_point" src="./images/circle.png"/>');
}
function person () {
var date;
date=prompt('Birthday date','01/01/1935');
var elem = date.split('/');
var month= elem[1]; //we take the month
var year=elem[2]; //we take the year
var mon= num2mon(month);
var rw=document.getElementById("table").rows.length;
var cols = $("#table").find('tr')[0].cells.length;
position(year,mon);
draw();
}
function draw() { //this function draw the lines
var table = document.getElementById("table");
var images = table.getElementsByTagName("img");
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var x,y;
canvas.width = table.offsetWidth;
canvas.height = table.offsetHeight;
function connect(image) { //this function link the images
var tabBcr = table.getBoundingClientRect();
var imgBcr = image.getBoundingClientRect();
ctx.beginPath();
ctx.moveTo(x, y);
x = imgBcr.left + (imgBcr.width / 2) - tabBcr.left;
y = imgBcr.top + (imgBcr.height / 2) - tabBcr.top;
ctx.lineTo(x, y);
ctx.stroke();
//ctx.fill(); //that's no work :S
//ctx.closePath();
}
for(var i=0; i<images.length; i++){
connect( images[i]);
}
}
謝謝!
畫布中有兩種路徑,主路徑和子路徑。
要近距離工作,您只需要最多一個子路徑。 每次使用moveTo()時都會創建一個新的子路徑,所以當一行像這樣:
moveTo(x1, y1);
lineTo(x2, y2);
moveTo(x2, y2);
lineTo(x3, y3);
您有兩個未連接的子路徑。 你想要的是繼續添加到現有子路徑的行,如下所示:
moveTo(x1, y1);
lineTo(x2, y2);
lineTo(x3, y3);
現在可以關閉連接x3-> x1和y3-> y1的形狀。
在這種情況下使用ctx.beginPath()
會使其最糟糕。 它將清除添加到主路徑的所有子路徑。
您需要做的是全局(或在更高級別)使用beginPath()
創建新路徑(例如,每次需要重繪內容時)。
然后需要使用moveTo()
設置第一行。 然后使用lineTo()
每隔一行。
最后你可以使用closePath()
並使用stroke()
或fill()
渲染它stroke()
fill()
不需要closePath(),必須在描邊之前調用它)。
例如 (未經測試,根據需要采用):
function draw() { //this function draw the lines
var table = document.getElementById("table");
var images = table.getElementsByTagName("img");
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var x,y;
canvas.width = table.offsetWidth;
canvas.height = table.offsetHeight;
function connect(image, index) { //this function link the images
var tabBcr = table.getBoundingClientRect();
var imgBcr = image.getBoundingClientRect();
x = imgBcr.left + (imgBcr.width / 2) - tabBcr.left;
y = imgBcr.top + (imgBcr.height / 2) - tabBcr.top;
index === 0 ? ctx.moveTo(x, y) : ctx.lineTo(x, y);
}
// new path here
ctx.beginPath();
for(var i=0; i<images.length; i++){
connect( images[i], i); // provide index so we can sep. move/line
}
// then at the end:
ctx.fill();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.