使用什么元素:背景图像 + 图像(形状)+ 画布中的文本
问题:没有在画布背景图像上方显示文本。
我所期望的:在图像上方显示带有颜色背景图像的文本。
我所拥有的:如果删除图像makeShape()功能,它将显示文本。注意:图像函数有背景颜色。
这是一个 HTML 表单代码:
<!doctype html>
<html lang="en">
    <head>
        <title>Canvas text above picture</title>    
        <meta charset="utf-8">
        <style>
            canvas {
                border: 2px solid black;
            }
        </style>
    </head>
    <body>
<form>
<p>
<label for="backgroundColor">Text font:</label>
<select id="backgroundColor">
<option value="white" selected="selected">White</option>
<option value="black">Black</option>
</select>
</p>
<p>
<label for="txt">Text font:</label>
<textarea id="txt" cols="40" rows="3"></textarea>
</p>
<p>
<input type="button" id="previewButton" value="Preview">
</p>
</form>
        <canvas id="myCanvas" width="600" height="500"></canvas>
        <script src="canvasshirt.js"></script>
    </body>
</html>
一个canvasshirt.js代码:
window.onload = function() {
    var button = document.getElementById("previewButton");
    button.onclick = previewHandler;
}
function previewHandler() {
    var ca = document.getElementById("myCanvas");
    var co = ca.getContext("2d");
    var bgcolor = document.getElementById("backgroundColor");
    var index = bgcolor.selectedIndex;
    var fgColor = bgcolor[index].value;
    var text = document.getElementById("txt").value;
    drawText(co, text); // ! - this should show text above of drawBckg() function
    drawBckg(ca, co, 600, 500, fgColor); // this draw a background of picture below of text
}
function drawBckg(ca, co, w, h, color)
{
    makeShape(co);
    co.fillStyle = color;
    co.fillRect(0, 0, w, h);
}
function makeShape(co)
{
    var shapeimg = new Image();
    shapeimg.src = "shape2.png";
    shapeimg.onload = function() {
        co.drawImage(shapeimg, 170, 10, 233, 350);
    }
}
function drawText(co, text)
{
    co.font = " 13px Arial";
    //co.font = "bold 1em sans-serif";
    co.textAlign = "left";
    co.fillText(text, 20, 40);
}
固定试...
当更改源代码的功能排序时,将导致以下结果:
drawBckg(ca, co, 600, 500, fgColor);
drawText(co, text);
示例图片(文字在图片下方):
