[英]Draw with canvas Javascript
也许你可以建议我,我需要用图像的坐标作为顶点绘制画布,但我把图像放到一个表(html表)所以我不知道该怎么做,如何在里面画画桌子或桌子上方。 例如,你有一个坐标(60,90)上的图像(79,45)和另一个(70,64)上的图像,我需要用这个坐标做一个三角形,但图像是一个表格(每个图像在不同的细胞。这是我的绘图代码:
function draw(elem) { //elem is the image
var image= elem;
var position = image.getBoundingClientRect();
//alert(posicion.top+" "+ posicion.right+" "+posicion.bottom+" "+posicion.left);
var canvas = document.getElementById('myCanvas');
var contexto = canvas.getContext('2d');
contexto.beginPath();
contexto.moveTo(position.top,50);
contexto.lineTo(position.top,150);
contexto.lineTo(position.top+100,150);
contexto.fill();
}
这是我的画布:
<canvas id="myCanvas" width="700" height="700">Your browse don't support canvas</canvas>
我把它放在表格代码下,我在其他函数中调用该函数。 如果你能帮助我,那就太好了。 谢谢!
我希望我能正确理解你的问题:你在实际的Table元素( <table></table>
)中有图像,在某些单元格中有图像。 您在其下方放置了一个画布,您想要绘制线条以连接表格中的图像。
要做到这一点,只需从图像的绝对位置中减去canvas元素的绝对位置。 这将使图像相对于画布的位置。
例如
var canvas = document.getElementById('myCanvas');
var canvasPos = canvas.getBoundingClientRect();
var position = image.getBoundingClientRect();
var x = position.left - canvasPos.left;
var y = position.top - canvasPos.top;
var contexto = canvas.getContext('2d');
contexto.beginPath();
contexto.moveTo(x, y);
... next image
假设您在父母中有一张桌子和画布,如:
<div id="wrapper">
<canvas id="lines"></canvas>
<table id="table">
<!-- 7*7 -->
</table>
</div>
#wrapper{
position:relative;
margin:0 auto;
width: 700px;
height:700px;
}
#wrapper canvas{
display:block;
position:absolute;
}
#wrapper table{
position: absolute;
}
#wrapper table td{
background: rgba(0,0,0,0.1);
width: 100px;
height: 100px;
vertical-align: middle;
}
#wrapper table td img{
display: block;
opacity:0.4;
}
您需要使用线条连接图像,
您可能对图像中心感兴趣,但您还需要考虑父偏移,因此您需要从每个图像的brc
(getBoundingClientRect)中减去该位置,并且它是td
parentNode高度/宽度:
var table = document.getElementById("table");
var images = table.getElementsByTagName("img");
var canvas = document.getElementById("lines");
var ctx = canvas.getContext("2d");
var x, y; // Remember coordinates
canvas.width = table.offsetWidth;
canvas.height = table.offsetHeight;
function connect( image ) {
var im = new Image();
im.onload = function(){ // make sure image is loaded
var tabBcr = table.getBoundingClientRect();
var imgBcr = image.getBoundingClientRect();
ctx.beginPath();
ctx.moveTo(x, y);
x = imgBcr.left + (image.parentNode.offsetWidth / 2) - tabBcr.left;
y = imgBcr.top + (image.parentNode.offsetHeight / 2) - tabBcr.top;
ctx.lineTo(x, y);
ctx.stroke();
};
im.src = images[i].src;
}
for(var i=0; i<images.length; i++){
connect( images[i] );
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.