2012-02-25 44 views
0

我有一個ASP.NET Razor視圖這樣的:如何調用JavaScript爲每個表格行畫一個畫布?

@{ 
    this.Layout = null; 
} 
<script type="text/javascript"> 

    function drawWindArrow(canvas, windDirection) { 
     // Draw something 
} 

</script> 

<table style="width: 100%"> 
    @foreach (var weather in ViewBag.WeatherForecastList) 
    { 
     double windDirection = weather.WindDirection; 
     <tr> 
      <td> 
       <canvas width="32" height="32"></canvas> 
       How can I call drawWindArrow with the canvas and the windDirection as a parameter??? 
      </td> 
     </tr> 
    } 
</table> 

我想這是爲表中的每一行不同的畫布上畫點什麼。它應該類似於這裏找到箭頭:http://www.yr.no/sted/Norge/Oslo/Oslo/Oslo/,但我不希望使用靜態圖片,因爲我需要基於一些CSS3的款式不同的顏色來繪製。

我怎麼能說與畫布和windDirection作爲參數drawWindArrow JavaScript函數?

+0

VAR可以= document.createElement(「canvas」); https://developer.mozilla.org/en/Canvas_tutorial/Drawing_shapes – 2012-02-25 07:57:30

+0

那麼,創建一個Canvas並繪製它很簡單。但是,對於每個具有不同參數的表格行,我該怎麼做呢? – Olav 2012-02-25 08:23:42

回答

0

你想爲你的箭頭事情的對象。這應該讓你在右腳。

var TableCanvasObject = function (arrowDirection, arrowType, container, id) { 
    this.container = container; 
    this.canvas = null; 
    this.ctx = null; 
    this.createArrow = function() { 
     if (arrowType == "foo") { 
      //draw arrow foo 
     } else if (arrowType = "boo") { 
      //draw arrow boo 
     } 
    }; 
    this.create = function() { 
     this.canvas = document.createElement("canvas"); 
     this.canvas.id = id; 
     this.ctx = this.canvas.getContext("2d"); 
     this.createArrow(); 
    }; 
    this.create(); 
    this.display = function() { 
     container.append(this.canvas); 
    } 
}; 


window.onload = function() { 
    var obj = new TableCanvasObject(90, "foo", document.getElementById("con"), "my thing"); 
    obj.display(); 
}; 
+0

上面的代碼似乎爲整個頁面創建了一個Canvas。我如何做到這一點在我的表的每一行中的單元格? – Olav 2012-02-27 18:44:39

+0

您創建一個畫布對象並放置在您想要的任何容器中。唯一的要求是容器必須有一個id: – 2012-02-27 19:39:46

0

我終於寫好了工作代碼。

這是我做的:

1)定義在我的ASP.NET Razor視圖元素在我的畫布。注意在Canvas元素上使用HTML5數據屬性。它們被用來將值傳遞給我的JavaScript函數,將畫在畫布元素內的天氣箭頭:

<td> 
    @string.Format("{0:f1}m/s ", weather.WindSpeed) 
    <canvas width="32" height="32" data-windSpeed="@(weather.WindSpeed)" data-windDirection="@(weather.WindDirection)"> 
    </canvas> 
    <br /> 
    @weather.WindSpeedName 
</td> 

2)HTML內容加載到內容能夠吸引到所有的畫布元素後的JavaScript函數被調用在位於特定的表元素:

function drawWindArrows() { 
    $('#weather canvas').each(function() { 
     var parent = this.parentNode; 
     var style = window.getComputedStyle(parent, null); 
     var color = style.color; 
     var windSpeed = $(this).attr('data-windSpeed'); 
     var windDirection = $(this).attr('data-windDirection'); 
     drawWindArrow(this, color, windSpeed, windDirection); 
    }); 

} 

function drawWindArrow(canvas, color, windSpeed, windDirection) { 
    // Draw inside the canvas 
} 

你可以看到完成的網頁瀏覽:

http://olavtlocation.cloudapp.net/weather

相關問題