在画布中绘制数组图像?

时间:2013-03-08 08:50:11

标签: javascript android cordova canvas

我正在尝试在画布上绘制一系列图像,但没有任何东西被绘制出来!以下是我的代码!此外,我正在尝试了解phonegap和javascript 的index.html:

    <!DOCTYPE html>
<html>
<head>
<title>Minecraft Background Check</title>
</head>
<body>
<canvas id="mycanvas" style="position:fixed; top:0; left:0; border:1px solid #c3c3c3; width: 100%; height: 100%;"></canvas>
<script type="text/javascript" src="cordova-2.5.0.js"></script>
<script type="text/javascript">
document.addEventListener("deviceready",ondeviceReady,false);
function onDeviceReady () {}
    //get element by id 
var c = document.getElementById("mycanvas");
var ctx = c.getContext("2d");
    //array image which need to draw in canvas
var image = ["img/image12","img/image13","img/image14","img/image15","img/image10"];
var m_arrImages = {};
for (var src in image) {
    m_arrImages[src] = new Image();

    m_arrImages[src].src = image[src];
}
var imagePositionsX = [20, 80, 140, 200, 260, 320, 380, 440, 500, 560];
var imagePositionsY = [20, 60, 100, 140, 180, 220, 260, 300, 340, 380];
var i, x, y;
for (i = 0; i < m_arrImages.length; i++) {
    x = imagePositionsX[ Math.floor(Math.random()*10) ];
    y = imagePositionsY[ Math.floor(Math.random()*10) ];

    ctx.drawImage(m_arrImages[i], x, y, 50, 50);
}
</script>
</body>
</html>

2 个答案:

答案 0 :(得分:2)

您已将函数ondeviceReady设置为在deviceready事件中运行,但未定义该函数。您已定义了一个名为onDeviceReady的函数。 Javascript变量和函数名称区分大小写,因此deviceready事件不会运行任何内容。

变化:

document.addEventListener("deviceready",ondeviceReady,false);

document.addEventListener("deviceready",onDeviceReady,false);

答案 1 :(得分:1)

可能是我错了,但是......“m_arrImages” - 它只是带字符串的数组,而不是图像,不是吗?

我觉得,它应该是这样的:

var m_arrImages = {};
for (var src in image) {
    m_arrImages[src] = new Image();
    m_arrImages[src].src = image[src];
}