大致目的:
- 通过 fetch() 获得线条位置等数据
- 在 HTML 的
<canvas>
元素中绘制线条 - 将获得的附带的文字数据通过绑定 Vue 显示。
<html>
<head>
<title>test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://cdn.bootcss.com/qs/6.5.1/qs.min.js"></script>
</head>
<body>
<div id="displayer_1">
<div v-if="successfully_loaded">
<h1>{{title}}</h1>
<canvas id="main_canvas" width="800" height="800" style="background-color: cyan;"></canvas>
</div>
<div v-else>
<h1>正在加载</h1>
</div>
</div>
<script>
var main_canvas = document.getElementById('main_canvas');
var ctx = main_canvas.getContext('2d');
// test rectangle
ctx.beginPath();
ctx.lineWidth = "5";
ctx.strokeStyle = "red";
ctx.rect(20,20 , 40,60);
ctx.stroke();
function draw_line(x1,y1 , x2,y2){
ctx.beginPath();
ctx.lineWidth = "5";
ctx.strokeStyle = "purple";
ctx.moveTo(x1,y1);
ctx.lineTo(x2,y2);
ctx.stroke();
}
// test draw line
draw_line(10,10 , 60,100)
new Vue({
el: '#displayer_1',
data: {
title: 'test',
lines: [],
successfully_loaded: false
},
created: function(){
const query = Qs.parse(location.search.substring(1))
result_filename = query.f
fetch('/data.json')
.then(response => response.json())
.then(json => {
this.title = json.title
this.lines = json.lines
console.log(this)
this.successfully_loaded = true
// Then, draw the lines ...
draw_line(100,100 , 700 , 700);
})
}
})
</script>
</body>
</html>
以上 js 代码中,我先绘制了一个测试矩形和一个测试线条,再在加载数据后也绘制线条。但其运行时只显示一个空的蓝绿(cyan)底色画板。
但是,如果将 <canvas>
元素移出 Vue 绑定的 id=displayer_1
的元素,一切绘制正常:
<div id="displayer_1">
<div v-if="successfully_loaded">
<h1>{{title}}</h1>
</div>
<div v-else>
<h1>正在加载</h1>
</div>
</div>
<!-- canvas 移出 Vue 绑定的元素 -->
<canvas id="main_canvas" width="800" height="800" style="background-color: cyan;"></canvas>
也许是 Vue 会对自己管理下的 canvas 子元素进行什么操作吧?