[英]Problem with Drawing Text on an Arc in Canvas using Javascript
我想使用Javascript在HTML畫布上的弧形上繪制“用戶提供的文本”。 這是我見過的最接近靈魂的例子: 使用畫布創建弧形文本
但是在我的代碼中,我一直得到一個“未捕獲的TypeError:無法讀取屬性'getContext'為null”我哪里錯了?
HTML
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
#canvas{
display:block;
margin:0 auto;
}
</style>
<script src="textOnPath3.js"></script>
</head>
<body>
<canvas id="myCanvas" width="900" height="400" style="border:1px solid #ff0000;"></canvas>
</body>
</html>
JAVASCRIPT
window.addEventListener("load", eventWindowLoaded, false);
var canvas = document.getElementById('myCanvas'),
context = canvas.getContext('2d'),
centerX = canvas.width / 2,
centerY = canvas.height - 30,
angle = Math.PI * 0.8,
radius = 150;
context.font = '30pt helvetica';
context.textAlign = 'center';
context.fillStyle = 'red';
context.strokeStyle = 'blue';
context.lineWidth = 4;
drawTextAlongArc(context, 'Arc Canvas Text', centerX, centerY, radius, angle);
// draw circle underneath text
context.arc(centerX, centerY, radius - 10, 0, 2 * Math.PI, false);
context.stroke();
function eventWindowLoaded () {
drawTextAlongArc();
}
function drawTextAlongArc(context, str, centerX, centerY, radius, angle) {
var len = str.length, s;
context.save();
context.translate(centerX, centerY);
context.rotate(-1 * angle / 2);
context.rotate(-1 * (angle / len) / 2);
for(var n = 0; n < len; n++) {
context.rotate(angle / len);
context.save();
context.translate(0, -1 * radius);
s = str[n];
context.fillText(s, 0, 0);
context.restore();
}
context.restore();
}
問題是雖然你已經添加了一個事件監聽器來檢查頁面是否已完成加載,但它只會調用函數eventWindowLoaded 。
這意味着此行之后的所有其他命令
window.addEventListener("load", eventWindowLoaded, false);
無論是否加載,都會被調用。
所以一旦到達
context = canvas.getContext('2d')
它會因你得到的錯誤而失敗。 html canvas元素尚不可用,因此canvas的值將是未定義的。
要修復此事件,將所有內容包裝在eventWindowLoaded函數中,如:
window.addEventListener("load", eventWindowLoaded, false);
function eventWindowLoaded() {
var canvas = document.getElementById('myCanvas');
context = canvas.getContext('2d');
centerX = canvas.width / 2;
centerY = canvas.height - 30;
angle = Math.PI * 0.8;
radius = 150;
context.font = '30pt helvetica';
context.textAlign = 'center';
context.fillStyle = 'red';
context.strokeStyle = 'blue';
context.lineWidth = 4;
drawTextAlongArc(context, 'Arc Canvas Text', centerX, centerY, radius, angle);
// draw circle underneath text
context.arc(centerX, centerY, radius - 10, 0, 2 * Math.PI, false);
context.stroke();
drawTextAlongArc();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.