[英]Images on first load don't show on canvas
我想传递一张图像列表,并将它们分别绘制在画布上。
我的view.py
:
def myview(request):
...
lista=Myobject.objects.filter(tipo=mytipo)
numero_oggetti = range(len(lista))
lista_formattata=[]
for elem in lista:
lista_formattata.append('/media/'+str(elem.myfield))
context_dict['lista']=lista_formattata
context_dict['numero_oggetti']=numero_oggetti
return render(request, 'mytemplate.html', context_dict)
我的template.html
:
<script>
<!--
window.onpageshow = function() {
myfunction({{lista|safe}});
};
-->
</script>
{% for c in numero_oggetti %}
<canvas id='componenti_canvas{{ c }}' width='60' height='75' style="border:1px solid #000000;">
Your browser does not support the HTML5 canvas tag.
</canvas>
{% endfor %}
我的script.js
:
function myfunction(lista) {
lista=lista
for (i=0; i<lista.length; i++) {
var canvas = document.getElementById('componenti_canvas'+i);
var ctx = canvas.getContext("2d");
var base = new Image();
base.src = lista[i];
ctx.scale(0.5,0.5);
ctx.drawImage(base, 0, 0);
};
};
此代码有效,但有时图像显示,有时却不显示(全部显示或全部显示)。 当我加载页面时,它们不显示,当我重新加载页面时,它们显示。 如果我等了几分钟再重新加载,它们将不再显示。
我正在使用firefox,并且在控制台日志中说不显示GET image_name.png HTTP/1.0 200
(有时它们在高速缓存中,有时没有...这没什么关系),当它不显示时什么也不要说。
我试过了:
setTimeout
-使用ajax
请求调用列表,该请求的cache: false
, async: false
base.onload
,像这样:
base.onload = function(){
ctx.scale(0.5,0.5);
ctx.drawImage(base, 0, 0);
}
但是,或者图像从不显示或以这种方式显示。 我可以提供详细信息,当然我可以做一些错误。
编辑 :在评论中说要使用onload。
我的script.js
:
function myfunction(lista) {
lista=lista
for (i=0; i<lista.length; i++) {
var canvas = document.getElementById('componenti_canvas'+i);
var ctx = canvas.getContext("2d");
var base = new Image();
base.onload = function() {
ctx.drawImage(base, 0, 0);
};
base.src = lista[i];
ctx.scale(0.5,0.5);
};
};
它仅在最后一个画布上绘制最后一个图像(我有很多画布,每个画布我都绘制一个图像)。
这将不起作用,因为您在循环的每次迭代中都会覆盖图像。 只有一个变量称为base,它只能保存一幅图像,因此所有图像都将丢失。
function myfunction(lista) {
lista=lista
for (i=0; i<lista.length; i++) {
var canvas = document.getElementById('componenti_canvas'+i);
var ctx = canvas.getContext("2d");
var base = new Image(); // second and more loops you over write base
base.onload = function() {
ctx.drawImage(base, 0, 0); // when it load only the last image is in base
// there is only one var called base so it
// can not hold more than one image
};
base.src = lista[i];
ctx.scale(0.5,0.5);
};
};
使用函数包装所有必需的变量,以便为每个图像创建唯一的集合。
function myfunction(lista) {
lista.forEach((name,i)=>{ // each time the call back is called a
// new set of variables are created to
// store each unique image.
var base = new Image();
base.src = name;
base.onload = function() { ctx.drawImage(base, 0, 0); };
var canvas = document.getElementById('componenti_canvas'+i);
var ctx = canvas.getContext("2d");
ctx.scale(0.5,0.5);
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.