Skip to content

Instantly share code, notes, and snippets.

@daysv
Created June 12, 2020 08:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daysv/2b9e937a0cbb4c88d6fcff51573eb66d to your computer and use it in GitHub Desktop.
Save daysv/2b9e937a0cbb4c88d6fcff51573eb66d to your computer and use it in GitHub Desktop.
add canvas watermark
;(function(context) {
function WaterMarker() {
this.config = {
fontSize: 12,
marginBottom: 100,
marginRight: 100,
angle: 30,
opacity: 0.08
}
}
WaterMarker.prototype.getWaterMarkText = function () {
var text = "water marker";
return text;
}
WaterMarker.prototype.addCanvasWaterMark = function (canvas) {
var text = this.getWaterMarkText();
var size = this.config.fontSize;
var marginBottom = this.config.marginBottom;
var marginRight = this.config.marginRight;
var ctx = canvas.getContext("2d");
ctx.globalAlpha = this.config.opacity;
ctx.font = "bold " + size + "px microsoft yahei";
ctx.fillStyle = "#888";
var metrics = ctx.measureText(text);
var width = metrics.width;
ctx.translate(canvas.width / 2, canvas.height / 2);
ctx.rotate(Math.PI / 180 * this.config.angle);
ctx.translate(-canvas.width, -canvas.height);
ctx.scale(2, 2);
var textWidth = width + marginRight;
var textHeight = size + marginBottom;
var countY = canvas.height / textHeight;
var countX = canvas.width / textWidth;
for (var y = 0; y < countY; y++) {
for (var x = 0; x < countX; x++) {
var offset = y % 2 === 0 ? 0 : textWidth / 2;
ctx.fillText(text, x * textWidth - offset, y * textHeight);
}
}
ctx.restore();
}
const waterMarker = new WaterMarker();
context.waterMarker = waterMarker;
})(this);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment