我正在创建一个名为 functions.js 的文件,其中包含不同的功能,例如:
- 图像()
- 绘制图像()
- 设置文本()
我的问题是我的文字一直落后。
我想要做的是,当我调用 setText() 时,我可以将文本放在我想要的地方。并且文本将放在 convas 的顶部。我知道我需要首先调用图像绘制加载函数以使它们不会覆盖我的文本。但我在我的 JS 中这样做了。
因此,在绘制/设置所有图像之后,我可以根据需要多次调用函数 setText() 并且文本将可见,这一点非常重要。
我想要顶部的文字。
这是我的代码:
函数.js
var canvas = "";
var context = "";
function canvasInit() {
canvas = document.getElementById('myCanvas');
context = canvas.getContext('2d');
}
function bgImage() {
var imageObj = new Image();
imageObj.onload = function() {
var pattern = context.createPattern(imageObj, 'repeat');
context.rect(0, 0, canvas.width, canvas.height);
context.fillStyle = pattern;
context.fill();
};
imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/wood-pattern.png';
}
function drawImage() {
var imageObj = new Image();
imageObj.onload = function() {
context.drawImage(imageObj, 10, 50);
context.drawImage(imageObj, x, y, width, height);
};
imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg';
}
function (text) {
context.font = 'italic 40pt Calibri';
context.fillText(text, 150, 100);
}
索引.html
<!DOCTYPE html>
<html>
<head>
<script src="functions.js"></script>
<script>
document.addEventListener('DOMContentLoaded',ready);
function ready() {
canvasInit();
bgImage();
drawImage();
setText("Yo");
setText("heyyyy");
}
</script>
</head>
<body>
<canvas id="myCanvas" width="500" height="400"></canvas>
</body>
</html>
更新了不起作用的测试:
索引.html
<!DOCTYPE html>
<html>
<head>
<script src="functions.js"></script>
<script>
document.addEventListener('DOMContentLoaded',ready);
function ready() {
canvasInit();
bgImage(function() {
setText();
});
}
</script>
</head>
<body>
<canvas id="myCanvas" width="500" height="400"></canvas>
</body>
</html>
函数.js
var canvas = "";
var context = "";
function canvasInit() {
canvas = document.getElementById('myCanvas');
context = canvas.getContext('2d');
}
function bgImage(callback) { // add parameter for function
var imageObj = new Image();
imageObj.onload = function() {
var pattern = context.createPattern(imageObj, 'repeat');
context.rect(0, 0, canvas.width, canvas.height);
context.fillStyle = pattern;
context.fill();
if (typeof callback === 'function') {
callback(); // invoke callback function
}
};
imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/wood-pattern.png';
}
function drawImage() {
var imageObj = new Image();
imageObj.onload = function() {
context.drawImage(imageObj, 10, 50);
context.drawImage(imageObj, x, y, width, height);
};
imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg';
}
function setText() {
context.font = 'italic 40pt Calibri';
context.fillText("Yoo adfa ds asd a sd", 150, 100);
}