如何在动态旋转值的HTML5 Canvas中绘制水印?

时间:2013-05-27 10:21:41

标签: javascript html5 html5-canvas

我在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演示”)。我试图通过多种方式来做,但我没有成功。

1 个答案:

答案 0 :(得分:4)

以下是一些改进的代码:

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