1. Use Canvas to add watermarks to pictures
Method notes:
- GetContext: Returns an environment to draw on the canvas.
Grammar: Canvas. GetContext (contextID)
The: contextID parameter specifies the type you want to draw on the canvas. The only current legal value is “2d”, which specifies 2d drawing and causes the method to return an environment object that exports a 2D drawing API.
- DrawImage: Draws an image, canvas, or video on a canvas. Can also draw parts of an image and/or increase or decrease the size of the image.
Syntax 1: context.drawImage(img,x,y)———— Locates the image on the canvas
Syntax 2: context.drawImage(img,x,y,width,height)———— Locates the image on the canvas and specifies the width and height of the image
Grammar 3: context. DrawImage (img, sx, sy, swidth, sheight, x, y, width, height) — – shear image, and positioning on the canvas is a part of the shear
Parameter values:
parameter describe img Specify the image, canvas, or video to use. sx Optional. The x position at which the shear began. sy Optional. The y position where the shear started. swidth Optional. The width of the clipped image. sheight Optional. The height of the clipped image. x Place the x position of the image on the canvas. y Place the y coordinate position of the image on the canvas. width Optional. The width of the image to use. (Stretch or zoom out image) height Optional. The height of the image to use. (Stretch or zoom out image)
- FillText: Text that is colored on a canvas. The default color of text is black.
Grammar: context. FillText (text, x, y, maxWidth)
Parameter values:
parameter describe text Specifies the text to be output on the canvas. x Start drawing the x-coordinate position of the text relative to the canvas. y Start drawing the y-coordinate position of the text relative to the canvas. maxWidth Optional. The maximum allowed text width, in pixels.
- Rotate: Rotates the current drawing.
Grammar: context. The rotate (Angle)
Parameter values:
parameter describe angle Angle of rotation, in radians. To convert degrees to radians, use degrees* math.pi /180. For example, if you want to rotate 5 degrees, specify the following formula: 5 * math.pi /180.
toDataURL
: returns a data URI containing the image presentation based onBase64
coding
Syntax: Canvas. toDataURL(type, encoderOptions);
Parameter values:
parameter describe type Optional. The default image format is image/ PNG. (Image/PNG, image/ JPEG, image/webp) encoderOptions Optional. Picture quality. When you specify image format as Image/JPEG or image/webp, you can select the image quality from 0 to 1. If the value is out of range, the default value 0.92 is used. Other parameters are ignored.
- ToBlob: Creates Blob objects that display images on the canvas
Syntax: Canvas. toBlob(callback, type, encoderOptions)
Parameter values:
parameter describe callback Callback function to get a single Blob object argument. type Optional. The default image format is image/ PNG. (Image/PNG, image/ JPEG, image/webp) encoderOptions Optional. Picture quality. When you specify image format as Image/JPEG or image/webp, you can select the image quality from 0 to 1. If the value is out of range, the default value 0.92 is used. Other parameters are ignored.
Concrete implementation method
-
A separate watermark
<template>
<div class=' '>
<img src="@/assets/bg.png" alt="" ref="imageCon">
<button @click="handleAddWaterMarker">Add a watermark</button>
<img :src="image" alt="">
</div>
</template>
<script>
export default {
data () {
return {
image: "",}},methods: {
handleAddWaterMarker () {
let content = "I am a watermark.";
let imageCon = this.$refs.imageCon;// Get the image
let canvas = document.createElement("canvas");// Create canvas container
canvas.width = imageCon.width;// Set the canvas container width
canvas.height = imageCon.height;// Set the canvas container height
let ctx = canvas.getContext("2d");// Get a 2D brush
DrawImage (image, x position, y position, image width, image height);
ctx.drawImage(imageCon, 0.0, imageCon.width, imageCon.height);
// Set the style of the text brush
ctx.textAlign = 'left';// Set the text alignment
ctx.textBaseline = 'top';// Set the text baseline
ctx.font = "14px Microsoft Yahei";// Set the text font properties
ctx.fillStyle = "Rgba (255, 255, 255,0.25)"// Set the text font color
// Draw text ctx.fillText(text content, x position, Y position, maximum width of text) on canvas canvas
ctx.fillText(content, imageCon.width - (content.split("").length * 14 + 10), imageCon.height - (14 + 10), imageCon.width)//14 is the text size
this.image = canvas.toDataURL("image/png");// Print canvas to base64}}},</script>
Copy the code
Effect:
-
The watermark covers the picture
<template>
<div class=' '>
<img src="@/assets/bg.png" alt="" ref="imageCon">
<button @click="handleAddWaterMarker">Add a watermark</button>
<img :src="image" alt="">
</div>
</template>
<script>
export default {
components: {},
props: {},
data () {
return {
image: "",}},methods: {
handleAddWaterMarker () {
let content = "I am a watermark.";
let height = 80; // The vertical height between two watermarks
let width = 70; // The horizontal height between two watermarks
let fontSize = 14; // Watermark font size
let imageCon = this.$refs.imageCon;// Get the image
let canvas = document.createElement("canvas");// Create canvas container
canvas.width = imageCon.width;// Set the canvas container width
canvas.height = imageCon.height;// Set the canvas container height
let ctx = canvas.getContext("2d");// Get a 2D brush
DrawImage (image, x position, y position, image width, image height);
ctx.drawImage(imageCon, 0.0, imageCon.width, imageCon.height);
// Set the text brush style
ctx.textAlign = 'left';// Set the text alignment
ctx.textBaseline = 'top';// Set the text baseline
ctx.font = `${fontSize}px Microsoft Yahei`;// Set the text font properties
ctx.fillStyle = "Rgba (255, 255, 255,0.25)"// Set the text font color
// Draw text ctx.fillText(text content, x position, Y position, maximum width of text) on canvas canvas
ctx.rotate(17 * Math.PI / 180)// Text rotation Angle Settings
let i = 0, j = 0, waterMarkerWidth = content.split("").length * fontSize;
for (i = 0; i < imageCon.width / (waterMarkerWidth); i++) {
for (j = 0; j < imageCon.height / (height - 20); j++) {
if (j == 0) {
ctx.fillText(content, i * (waterMarkerWidth + width), -height, imageCon.width)
}
ctx.fillText(content, i * (waterMarkerWidth + width), j * height, imageCon.width)
}
}
// var image = new Image();
// imageCon.setAttribute('crossOrigin', 'anonymous'); / / across domains
// imageCon.setAttribute('useCORS', true); / / across domains
// image.setAttribute('crossOrigin', 'anonymous'); / / across domains
// image.setAttribute('useCORS', true); / / across domains
// image.src = canvas.toDataURL("image/png");
this.image = canvas.toDataURL("image/png");// Print canvas to base64}}},</script>
<style lang="less" scoped>
</style>
Copy the code
Effect:
2. Use DOM-to-image to add watermarks to images
Methods annotations
- EncodeURIComponent: Encodes the string as a URI component.
Grammar: encodeURIComponent (uri)
Parameter values:
parameter describe uri A necessity. A string containing the URI component or other text to be encoded.
- Unescape: Decodes the encoded string.
Grammar: unescape (string)
Parameter values:
parameter describe string A necessity. The string to decode.
- Btoa: Used to create a base-64 encoded string. Base-64 decoding using atOB ().
Grammar: window. Btoa (string)
Parameter values:
parameter describe string Required, the string to encode.
Concrete implementation method
<template>
<div class="">
<! HTML -->
<div class="preview" ref="previewImg">
<img :src="defaultimg" alt="" />
<div class="watermark" :style="{ background: watermark }"></div>
</div>
<button @click="handleAddWaterMarker">Add a watermark</button>
<! -- After converting to watermark -->
<img :src="image" alt="">
</div>
</template>
<script>
import DomToImage from "dom-to-image";
export default {
data () {
return {
defaultimg: require("@/assets/bg.png"),
watermark: "".image: "".watermarkOptions: {
text: "I am a watermark.".fontSize: 12.width: 20.color: "#fff".alpha: 20.rotate: 35}}; },methods: {
handleAddWaterMarker () {
// Text length
const wordWidth = this.watermarkOptions.fontSize * this.watermarkOptions.text.split("").length;
const width = wordWidth + this.watermarkOptions.width;
let svgText = `
<svg xmlns="http://www.w3.org/2000/svg" width="${width}px" height="${width}px">
<text x="50%" y="50%"
alignment-baseline="middle"
text-anchor="middle"
stroke="The ${this.watermarkOptions.color}"
opacity="The ${this.watermarkOptions.alpha / 100}"
transform="translate(${width / 2}, ${width / 2}) rotate(The ${this.watermarkOptions.rotate}) translate(-${width / 2}, -${width / 2})"
font-weight="100"
font-size="The ${this.watermarkOptions.fontSize}"
font-family="microsoft yahe"
>
The ${this.watermarkOptions.text}
</text>
</svg>`;
this.watermark = `url(data:image/svg+xml; base64,${btoa(unescape(encodeURIComponent(svgText)))}) `;
// Convert HTML to images
let node = this.$refs.previewImg, that = this;
DomToImage.toPng(node).then((dataUrl) = >{ that.image = dataUrl; }); }}};</script>
<style lang="less" scoped>
.preview {
display: inline-block;
position: relative;
margin-left: 20px;
width: 375px;
height: 668px;
img {
display: block;
}
.watermark {
position: absolute;
left: 0;
top: 0;
bottom: 0;
right: 0; }}</style>
Copy the code
Effect: