【问题标题】:How to add text in particular block of canvas如何在特定的画布块中添加文本
【发布时间】:2013-12-02 19:24:18
【问题描述】:

我想在我的画布的矩形块中添加文本。请告诉我该怎么做,我的代码在下面

 <html>
        <title>Canvas app</title>
        <head>
        <style>
        #canvas_ract{
            border:1px solid black;
        } 
        </style>
        <script>
              window.onload =function(){
                var myCanvas = document.getElementById('canvas_ract');
                var ctx = myCanvas.getContext("2d");
                ctx.beginPath();
                ctx.fillStyle="#FF0000";
                              //ctx.strokeStyle = "#0000bb";
                            ctx.arc(200,100,100,0,Math.PI*2,true);
                ctx.closePath();
                ctx.fill();
                ctx.font="30px Arial";
                ctx.fillText("Hello World",10,50);
                ctx.fillStyle="pink";
                ctx.fillRect(30,40,200,100);
                             }
        </script>
        </head>
        <body>
            <canvas id="canvas_ract" width="500"height="500"><canvas>

        </body>
    </html>

并告诉我是否有任何好的方法可以获取有关此画布 api 的更多知识

【问题讨论】:

    标签: php html canvas


    【解决方案1】:

    如果您的问题是如何添加文本“Hello World!”在粉红色矩形内,答案是颠倒您的 fillText 和 fillRectangle 调用的顺序。类似的东西:

    ctx.fillStyle="pink";
    ctx.fillRect(30,40,200,100);
    ctx.fillStyle="red";
    ctx.fillText("Hello World",35,70, 200,100);
    

    使用画布时,您需要知道您绘制的所有内容都堆叠在上一张绘图的顶部。您可以将其视为 css z-index 属性。这意味着最后一个画布语句将始终位于顶部。

    您可以看到一个矩形顶部的文本示例here

    正如 schopy 所说,http://diveintohtml5.info/canvas.html#text 是一个很好的参考或更技术性的参考https://developer.mozilla.org/en/docs/HTML/Canvas

    更新:如何添加图片

    首先您需要以编程方式创建一个图像对象,然后使用 drawImage 函数。可以这样做:

    var img = new Image();
    //Link to the image as if it where an img tag in your dom tree
    img.src = 'http://icons.iconarchive.com/icons/iconka/meow/96/cat-walk-icon.png';
    img.onload = function () {
      //Wait for the image to be loaded and continue with the canvas manipulation
      ctx.drawImage(img, 120,40);
      ctx.fillStyle = "red";
      ctx.fillText("Hello World", 35, 70, 200, 100);
    }
    

    Here is a 2nd example 里面有图片

    【讨论】:

      猜你喜欢
      • 2013-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-03
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      相关资源
      最近更新 更多