[英]Canvas drawing doesn't work in external .js file
我的腳本在包含在 html 文件中時有效,但是當我將其移動到 external.js 文件時,canvas 不會繪制。
這是我的 html 文件:
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<title>Reveal RGB Values</title>
<form action='/' method='POST' enctype='multipart/form-data'>
<h1>Select file to upload:</h1>
<br>
<input type='file' name='file'>
<input type='submit' value='submit'>
</form>
{% if status == 'uploaded'%}
<h1>There will be a photo here</h1>
<canvas id="frame"></canvas>
<canvas id= "solution_frame"></canvas>
<div id="solution"></div>
{% endif %}
<script type = text/javascript src="{{ url_for('static', filename='script.js') }}"></script>
</body>
在 external.js 文件中,我有兩個成功構建的畫布(我可以看到與大小匹配的空白)
var frame = document.getElementById('frame');
frame.width = 800;
frame.height = 600;
var context = frame.getContext('2d');
var solution_frame = document.getElementById('solution_frame');
var solution_context = solution_frame.getContext('2d');
solution_frame.width = 25;
solution_frame.height = 25;
但我無法繪制圖像
function draw_image(){
base_image = new Image();
// yay! jinja works here too.
var image_url = '{{img_url}}';
base_image.src = image_url;
base_image.onload = function(){
//context.drawImage(base_image, 0, 0);
scale_to_fit(this);
}
}
draw_image();
function scale_to_fit(img){
//get the scale
var scale = Math.min(frame.width/img.width, frame.height/img.height);
var x = (frame.width/2) - (img.width/2) * scale;
var y = (frame.height/2) - (img.height/2) * scale;
context.drawImage(base_image,x,y,img.width*scale, img.height*scale);
我發現了一個類似的帖子,建議我添加這個
document.addEventListener('DOMContentLoaded',draw_image,false);
說腳本在 canvas 完全加載之前起作用,但這似乎不是問題。
誰能看到我可能出錯的地方? 提前謝謝
編輯:? 我突然想到這個問題可能與使用 Jinja 檢索圖像源位置有關?
看來我的問題根本與 html/js 無關。 我正在使用 Jinja 從服務器檢索圖像位置,而 Jinja 不服務於該外部 js 文件。 在我看來,function 需要保存在 html 文件中。
這是正確的。 Jinja 不對靜態包含的資產進行任何處理。
我看到解決您的問題的兩種方法。
在script.js
中硬編碼 URL :
var image_url = '/path/to/image'
或者從draw_image
function 中刪除該行並在包含script.js
之前在模板中設置該 JS 變量:
<script type='text/javascript'>
const image_url = {{img_url}};
</script>
<script type='text/javascript' src="{{ url_for('static', filename='script.js') }}"></script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.