画布javascript的奇怪行为

时间:2014-08-19 05:49:18

标签: html5 canvas

var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');

var bee = new Image();

var height = 0, width = 0;



bee.onload = function () {
init();
}


init();

function init()
{



 console.log(ctx);
bee.src = '\\assets\\images\\ant_256.png';
width = canvas.width;
height = canvas.height;
console.log(height + '-' + width);
console.log(bee);
ctx.drawImage(bee, 10, 10, 10, 10);

}

你看我调用了Init();功能两次,如果我评论图片没有在我的画布上显示的任何功能,它现在如何显示

2 个答案:

答案 0 :(得分:1)

检查这段代码......我添加了jquery并在其onload上修复了一些DOM元素绑定序列

$(function () {
myCanvas = document.createElement('canvas');
canvas = document.querySelector('body').appendChild(myCanvas);
canvas.height = window.innerHeight;
canvas.width = window.innerWidth;
canvas.id = 'shipcanvas';
ctx = canvas.getContext('2d'); 

    bee.onload = function () { 
}

bee.src = '\\assets\\images\\ant_256.png';
    ctx.drawImage(name, x, y);



});

答案 1 :(得分:0)

ctx.drawImage(bee, 10, 10, 10, 10);
下载图像后,

需要发生,

开始下载

bee.src ='\ assets \ images \ ant_256.png';

是init函数的一部分。

第一次调用init开始下载而没有图像......

ctx.drawImage(bee, 10, 10, 10, 10);

...在下载图像之前无法绘制,目前不是第一次调用。

onload事件后第二次调用init绘制图像。

<强>解决方案

移动

 bee.src = '\\assets\\images\\ant_256.png';

到第一次调用init()的位置;这是页面中间的那个。

var canvas = document.getElementById('myCanvas'),
    ctx = canvas.getContext('2d'),
    bee = new Image(),
    height = 0,
    width = 0;

bee.onload = function () {
   init();
}

bee.src = '\\assets\\images\\ant_256.png';

function init() {
   console.log(ctx);
   width = canvas.width;
   height = canvas.height;
   console.log(height + '-' + width);
   console.log(bee);
   ctx.drawImage(bee, 10, 10, 10, 10);
}
相关问题