3

我正在使用 HTML5,我正在尝试使用文本在图像上绘制水印。我有以下代码:

<html>
    <body onload="addWaterMarkOnPage();">
        <div id="pageContainer" style="width: 612px; height: 792px;">
             <canvas id="page1" width="612" height="792"></canvas> //image loading canvas  
             </canvas>
        </div>
    </body>
<html>

JavaScript

 function addWaterMarkOnPage()
 {
var watermarkCanvas=document.createElement("canvas");
watermarkCanvas.id="watermark";
var parentDivElement=document.getElementById("pageContainer")
var parentCanvasElment=document.getElementById("page");

watermarkCanvas.width=parentCanvasElment.width;
watermarkCanvas.height=parentCanvasElment.height;
watermarkCanvas.setAttribute("style","position:absolute")


if(parentDivElement.firstChild)
    parentDivElement.insertBefore(watermarkCanvas, parentDivElement.firstChild);
else
    parentDivElement.appendChild(watermarkCanvas);

var watermarkContext=watermarkCanvas.getContext('2d');

watermarkContext.globalAlpha=0.5;


watermarkContext.beginPath();
var metrics = watermarkContext.measureText("WaterMark Demo");
var width = metrics.width;
watermarkContext.rotate( (Math.PI / 180) * -45);  //rotate 25 degrees
watermarkContext.font = "72px comic Sans MS" ;
watermarkContext.fillStyle = "Red";
watermarkContext.fillText("WaterMark Demo",-width*2,72);
watermarkContext.fill();

}

我想在页面中对角绘制文本(“WaterMark Demo”)。我尝试过多种方式,但没有成功。

4

1 回答 1

5

这是一些改进的代码:

var container=document.getElementById("pageContainer")
var origCanvas=document.getElementById("page1");
var wmCanvas=document.createElement("canvas");
wmCanvas.id="watermark";
wmCanvas.width=origCanvas.width;
wmCanvas.height=origCanvas.height;
wmCanvas.setAttribute("style","position:absolute;border:1px solid black")

if(container.firstChild)
    container.insertBefore(wmCanvas, container.firstChild);
else
    container.appendChild(wmCanvas);

var wmContext=wmCanvas.getContext('2d');
wmContext.globalAlpha=0.5;
// setup text for filling
wmContext.font = "72px Comic Sans MS" ;
wmContext.fillStyle = "red";
// get the metrics with font settings
var metrics = wmContext.measureText("WaterMark Demo");
var width = metrics.width;
// height is font size
var height = 72;

// change the origin coordinate to the middle of the context
wmContext.translate(origCanvas.width/2, origCanvas.height/2);
// rotate the context (so it's rotated around its center)
wmContext.rotate(-Math.atan(origCanvas.height/origCanvas.width));
// as the origin is now at the center, just need to center the text
wmContext.fillText("WaterMark Demo",-width/2,height/2);

工作地点:http: //jsfiddle.net/EAXc9/7/

深受启发:https ://stackoverflow.com/a/5400970/2249185

于 2013-05-27T10:54:14.363 回答