[英]Black canvas instead of image
I have a problem with canvas. 我的画布有问题。 Let's say, 1/10 time I have black square instead of my image, on chrome.
假设有1/10次在chrome上我有黑色正方形而不是图像。 My code is as follow, how can I modify it in order to avoid this black display?
我的代码如下,如何修改它以避免出现黑屏?
<canvas id="Canvas" width="954" height="267"></canvas>
<script>
var canvas = document.getElementById('Canvas');
var context = canvas.getContext("2d");
// Map sprite
var mapSprite = new Image();
mapSprite.src = 'image.png';
var main = function () {
draw();
};
var draw = function () {
// Clear Canvas
context.fillStyle = "#000";
context.fillRect(0, 0, canvas.width, canvas.height);
// Draw diagramme
context.drawImage(mapSprite, 0, 0, 954, 267);
}
main();
</script>
EDIT 1: full function draw : 编辑1:全功能绘制:
var draw = function () {
// Clear Canvas
context.fillStyle = "#000";
context.fillRect(0, 0, canvas.width, canvas.height);
// Draw diagramme
context.drawImage(mapSprite, 0, 0, nextWidth, nextHeight);
//draw all precedent cross
cross = new Image();
cross.src = "cross.png";
for (var i = 0; i < array_x.length; i++) {
context.drawImage(cross, array_x[i], array_y[i], 10, 10);
}
}
I believe you want to wait until image is loaded. 我相信您要等到图像加载完毕。
Replace: 更换:
main();
With: 附:
mapSprite.addEventListener('load', main);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.