html5 can,javascript - Problems with canvas html5 can't close a draw - Stack Overflow

There are two kind of paths in canvas, the main path and then sub-paths.

For a close to work you need to only have max one sub-path. Every time moveTo() is used a new sub-path will be created so when a line is made like this:

moveTo(x1, y1);

lineTo(x2, y2);

moveTo(x2, y2);

lineTo(x3, y3);

You have two sub-paths that are not connected. What you want is to continue adding lines to the existing sub-paths like this:

moveTo(x1, y1);

lineTo(x2, y2);

lineTo(x3, y3);

Now it is possible to close the shape connecting x3->x1 and y3->y1.

Using ctx.beginPath() in this case makes it worst. It will clear all sub-paths added to the main path.

What you need to do is to globally (or at some higher level) create a new path using beginPath() (every time you need to redraw the content for example).

Then the first line needs to be set using moveTo(). Then every other lines using lineTo().

Finally you can use closePath() and render it using stroke() or fill() (closePath() is not needed with fill, with stroke it must be called before stroke).

For example (untested, adopt as needed):

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

connect( images[i], i); // provide index so we can sep. move/line

}

// then at the end:

ctx.fill();

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值