JavaScript 将文本写入图像

标签 javascript jquery html

我在将文本写入图像时遇到问题。我需要循环图像。但我遇到一些问题。当我这样做时,最后一张图像显示并且图像尺寸很小。有人帮助我吗?

var div=document.getElementById("locations");
var canvas;

window.onload = function(){
    for(var i=0;i<10;i++){
        canvas=document.createElement("canvas");
        canvas.style.width="75px";
        canvas.style.height="75px"

        var context = canvas.getContext("2d");
        var imageObj = new Image();
        imageObj.onload = function(){
            context.drawImage(imageObj, 0, 0);
            context.font = "17px Calibri";
            context.fillText(i, 30, 36);
        };
        imageObj.src = "image.png"; 
        div.appendChild(canvas);
    };
}
<div id="locations"></div>
<canvas id="myCanvas" width="75" height="75"></canvas>

结果图像

Result Image

最佳答案

使用canvas.height和width值而不是CSS样式。绘制 Canvas 后应用 CSS 样式值。

var div=document.getElementById("locations");
var canvas;

window.onload = function(){
    for(var i=0;i<10;i++){
        canvas=document.createElement("canvas");
        canvas.width=75;
        canvas.height=75;

        var context = canvas.getContext("2d");
        var imageObj = new Image();
        imageObj.onload = function(){
            context.drawImage(imageObj, 0, 0);
            context.font = "17px Calibri";
            context.fillText(i, 30, 36);
        };
        imageObj.src = "http://placehold.it/350x150"; 
        div.appendChild(canvas);
    };
}
<div id="locations"></div>

关于JavaScript 将文本写入图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38279788/

相关文章:

javascript - 总金额显示为 NAN,javascript

javascript - replaceWith 替换所有文本而不是仅空字符串

jquery - 从我的服务器发送的静态内容(例如 : . css、.js)是否被 gzip 压缩?

javascript - 如何在javascript中回到数组的开头

php - session 在浏览页面 PHP 时获得另一个值

javascript - 有人可以帮我在按键后运行 CSS 动画吗?

javascript - Apps 脚本,将工作表范围转换为 Blob

javascript - 转换 :unchecked to prop ('checked' , 错误)

javascript - 点击时管理 <td> 类标签 - javascript

javascript - html - 如何动态更改网页的 url