我正在尝试在 HTML5 Canvas 上的无序列表中绘制图像。每个 li 元素内有 1 个 Canvas ,ul 内总共有 20 个 li。我使用下面的代码在 Canvas 上绘制图像,但是只有最后一个 Canvas 上绘制图像。我是 HTML5 新手,不太确定我做错了什么,但我肯定做错了什么。
<_ul id="ulDirectory" data-role="listview" data-filter="true">
<li data-role="fieldcontain" style="background: #dddddd; height: 80px">
<div class="ui-grid-a">
<div class="ui-block-a" style="width: 25%">
<canvas id="myCanvas<%: Html.DisplayFor(_m => item.EmployeeCode) %>" width="80" height="80" class="pull-left"></canvas>
</div>
<div class="ui-block-b" style="width: 75%; line-height: 25px">
<span><%: Html.DisplayFor(_m => item.FName) %> <%: Html.DisplayFor(_m => item.LName) %></span><br />
<span><%: Html.DisplayFor(_m => item.Mobile) %> | <%: Html.DisplayFor(_m => item.EmployeeCode) %></span><br />
<span><%: Html.DisplayFor(_m => item.Email) %></span>
</div>
</div>
</li>
</_ul>
<script type="text/javascript">
function displayImage() {`enter code here`
$("ul#ulDirectory > li").find("canvas").each(function () {
var myImage = new Image(); //**UPDATE**
canvas = this;
if (canvas.getContext) {
ctx = canvas.getContext("2d");
myImage.onload = function () {
ctx.drawImage(myImage, 0, 0, 80, 80);
ctx.strokeStyle = "white";
ctx.lineWidth = "25";
ctx.beginPath();
ctx.arc(40, 40, 52, 0, Math.PI * 2, true);
ctx.closePath();
ctx.strokeStyle = '#dddddd';
ctx.stroke();
}
myImage.src = "../../TempUpload/hitin831121.png";
}
});
$(document).ready(function () {
displayImage();
});
</script>
最佳答案
所有变量都属于全局范围,并且在每次迭代中都会被覆盖。
使用 var
关键字声明每个函数作用域内的变量。
$("ul#ulDirectory > li canvas").each(function () {
var canvas = this;
if (canvas.getContext) {
var ctx = canvas.getContext("2d");
var myImage = new Image();
myImage.onload = function () {
ctx.drawImage(myImage, 0, 0, 80, 80);
ctx.strokeStyle = "white";
ctx.lineWidth = "25";
ctx.beginPath();
ctx.arc(40, 40, 52, 0, Math.PI * 2, true);
ctx.closePath();
ctx.strokeStyle = '#dddddd';
ctx.stroke();
}
myImage.src = ...
这是一个 fiddle :http://jsfiddle.net/4Lozwkzq/1/
关于javascript - HTML5 Canvas 位于列表内,无法在所有列表上绘制图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27089340/