如何在特定的画布块中添加文本

时间:2013-11-19 09:51:26

标签: php html canvas

我想在画布的Rectangle块中添加文本。请让我知道我该怎么做,我的代码在下面

 <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的更多知识

2 个答案:

答案 0 :(得分:1)

您在这里有一篇关于canvas API的好文章http://diveintohtml5.info/canvas.html#text

答案 1 :(得分: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属性一样看到它。这意味着最后一个canvas语句将始终位于顶部。

您可以在矩形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