javascript HTML Canvas 不显示图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10593030/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HTML Canvas not displaying image
提问by debugoz
Im sure this has got to be something simple that I am overlooking, but I can't seem to get my canvas to display an jpg stored on the server.
我确定这一定是我忽略的一些简单的事情,但我似乎无法让我的画布显示存储在服务器上的 jpg。
<img id="test_img" alt="test" src="/media/tmp/a4c1117e-c310-4b39-98cc-43e1feb64216.jpg"/>
<canvas id="user_photo" style="position:relative;"></canvas>
<script type="text/javascript">
var image = new Image();
image.src = "/media/tmp/a4c1117e-c310-4b39-98cc-43e1feb64216.jpg";
var pic = document.getElementById("user_photo");
pic.getContext('2d').drawImage(image, 0, 0);
</script>
the <img>
displays as expected, however the canvas is blank, though it does seem to have the correct dimensions. Any one see what I'm doing wrong?
在<img>
如预期显示,但是在画布上是空白的,但它似乎有正确的尺寸。有人看到我做错了什么吗?
My tired eyes will appreciate any help.
我疲惫的眼睛会感激任何帮助。
Thanks
谢谢
回答by pollirrata
you may want to use the following approach
您可能想使用以下方法
image.onload = function() {
pic.getContext('2d').drawImage(image, 0,0);
}
so you ensure that the image is loaded when trying to draw it.
因此您可以确保在尝试绘制图像时加载图像。
回答by Laurent Perso
var initialFloorplanWidth = 0;
var initialFloorplanHeight = 0;
var canvasImage = new Image();
documentReady = function () {
preloadFloorplan();
}
preloadFloorplan = function () {
onLoad = function () {
initialFloorplanHeight = canvasImage.height;
initialFloorplanWidth = canvasImage.width;
var canvasHtml = '<canvas id="MainCanvas" width="' + initialFloorplanWidth + '" height="' + initialFloorplanHeight + '">Canevas non supportés</canvas>';
$("#MainContainer").append(canvasHtml);
var canvas = $("#MainCanvas")[0];
var canvasContext = canvas.getContext("2d");
canvasContext.drawImage(canvasImage, 0, 0);
}
canvasImage.onload = onLoad;
canvasImage.src = initialFloorplan;
}
This code works well.
这段代码运行良好。
回答by hvgotcodes
回答by lakam99
Maybe it's something to do with the rest of your code. Is "user_photo" identified in the code?
也许这与您的其余代码有关。代码中是否标识了“user_photo”?