簡體   English   中英

用畫布Javascript畫畫

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

jsBin演示

假設您在父母中有一張桌子和畫布,如:

<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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM