[英]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.