Add a watermark (canvas + drag) to the image in the blog garden ),

Source: Internet
Author: User

Add a watermark (canvas + drag) to the image in the blog garden ),
Preface I want to add a watermark to some of my pictures, so I am playing with such a thing.This function does not take compatibility into consideration (too lazy). It is only tested in Chrome. If you do not pass the test in IE Firefox, do not vomit.Because the download attribute is applied, you don't have to worry about IE or anything. If you are using Firefox, you can change the compatibility by yourself.If the code is F12, take it by yourself. There is no compression. (In the end, the original code is pasted into the blog and saved as a draft preview. The js Code is blocked after the release, it can only be written to the footer. You can also access the following github address to obtain the code: Code address. In addition, in order to get into the blog Park, the Code was changed from ES2015 to ES5, so it was a bit messy, but the necessary comments were added. It was so hard to give a thumbs up. To change the watermark style or something, you can change the attributes of this variable on the console.

Var watermarkInfo = {fontSize: 18, // The pixel value fontFamily: 'cursive ', content: '', color:' # fffbf0 '};
I will not talk much about it. I will directly upload the work. Select the background image, set the watermark text, drag the watermark text to any position, and click the download file button. Select background image <Input id = "target_file" type = "file"/>

However, the original file upload control is ugly, so you can hide the control and add a new button before it.

<A class = "btn" id = "btn_select_file" href = "jacasloud: void (0) "> select the background image </a> <input id =" target_file "type =" file "style =" display: none "/>

To select a file by clicking the select background image button, use the following code:

// Press the selected background image $ ('# btn_select_file'). click (function () {$ ('# target_file'). click ();});

After a file is selected, the file upload control triggers the change event and you can get the file.

$('#target_file').change(function (event) {    var imgFile = event.target.files[0];    ......});
Convert a file to an image

To convert a file to an image, you must read the file first. FileReader is used here.

Function setimg1_canvas (imgFile) {var reader = new FileReader (); reader. onloadend = function (e) {var dataURL = e.tar get. result; img. onload = function (event) {var ctx = document. getElementById ('target _ canvas '). getContext ('2d '); // set the canvas size to the same size as the image. setCanvasSize(event.tar get. naturalWidth, event.tar get. naturalHeight); ctx. drawImage (img, 0, 0); setCanvasImgToDownloadLink () ;}; img. src = dataURL;}; reader. readAsDataURL (imgFile); resetWatermark ();};

 

The above is the core code, through FileReaderOf ReadAsDataURLThe function reads the file to obtain the Image data in Base64 format and assigns the Image data to an Image object. After adding a watermark to the image and reading the above Code, there is a step in it to render the image into the canvas. In fact, the core function is to use canvas to add a watermark to the image. The operation is to first use the image DrawImageRender the image into the canvas, and then use FillTextRender the text and use the final canvas ToDataURLConvert to image data. For specific usage, refer to my code and check the canvas API. This kind of things is difficult for new users. It is actually very easy to describe it here. However, it will be troublesome. If it is a white watermark, the watermark on the image cannot be too different from the image color, or it will be difficult to find out. Therefore, the watermark position must be adjustable for different images. The initial solution is to specify two input boxes, input positions, and then render the watermark to the text. However, this solution first faces a usability problem. How can I obtain a specific location? I can only try it one by one. Not every user will use the software to find a location. So here we use the drag text scheme. Drag text watermark

Although canvas can also capture events, get the mouse position, and achieve the drag text effect, it is too troublesome to implement.

Therefore, a simpler solution is used here.

When we set a watermark, we directly render the text to the canvas, and place a color-transparent content above the text as the span element of the watermark text.

Then we add the drag event to this span element.

HTML5 drag function a lot of online, I will not talk about it here.

The following describes the implementation methods:

When you start to drag, use the image to render the canvas again, so that the previously rendered text disappears.

When the drag ends, get the specific position and render the text into the canvas again.

Here is simple, but there are still some details, including the combination of css and js, such as the processing method when the text is dragged to the boundary, and the line break when the text is dragged to the boundary.

There are also some other small pitfalls that you need to read and understand by yourself.

Some code is posted here:

// Bind the event var bindEvent4DragWatermark = function () {$ ('# watermark '). on ('dragstart', function (e) {var ctx = document. getElementById ('target _ canvas '). getContext ('2d '); ctx. clearRect (0, 0, $ ('# target_canvas '). width (), $ ('# target_canvas '). height (); ctx. drawImage (img, 0, 0); // drag the watermark to display $ (this ). addClass ('selected'); watermarkInfo. offsetX = e. originalEvent. offsetX + canvasInfo. left; watermarkInfo. offsetY = e. originalEvent. offsetY + canvasInfo. top ;}); // move the watermark with the mouse $ ('# watermark '). on ('drag', function (e) {var x = e. originalEvent. pageX; var y = e. originalEvent. pageY; if (x = 0 & y = 0) {return;} x-= watermarkInfo. offsetX; y-= watermarkInfo. offsetY; (('your watermark'}.css ('left', x0000.css ('top', y) ;}); $ ('# watermark '). on ('dragend', function (e) {// adjust the position so that the watermark cannot exceed the canvas boundary var x = e. originalEvent. pageX-watermarkInfo. offsetX; var y = e. originalEvent. pageY-watermarkInfo. offsetY; if (x <0) {x = 0;} if (y <0) {y = 0;} var maxX = canvasInfo. width-watermarkInfo. width; var maxY = canvasInfo. height-watermarkInfo. height; if (x> maxX) {x = maxX;} if (y> maxY) {y = maxY;} else ('{watermark'}.css ('left', x).css ('top ', y); // drag the watermark and hide the text $ ('# watermark '). removeClass ('selected'); setTextIntoCanvas () ;}); // disable the style when the mouse is not displayed $ ('# canvas-iner '). on ('dragover', function (e) {e. preventDefault ();});}
Download the Last Modified Image

We have already talked about using canvas.ToDataURLThe function obtains the final image data and then uses an HTML5 download attribute for download.

<A class = "btn" id = "download_file" href = "#" download = "watermark image"> download a merged image </a>

The following code sets the image data.

/*** Set the canvas image to the download link */function setCanvasImgToDownloadLink () {var imgData = document. getElementById ('target _ canvas '). toDataURL (); $ ('# download_file '). attr ('href ', imgData );};
Write functions into your blog

For this part, you must first apply for JS permissions.

Secondly, if you observe carefully, you can also see the following code in my code

// Insert html in this way because the blog garden automatically shields the canvas tag and the download attribute var initHtmlConstruct = function () {$ ('# canvas-iner '). text (''). append ('<canvas id = "target_canvas" width = "100" height = "100"> the browser does not support this function, upgrade </canvas> <span draggable = "true" id = "watermark"> </span> ') $ (' # toolbar '). append ('<a class = "btn" id = "download_file" href = "#" download = "watermark image"> download merged image </a> ');}

The cause comment is also written because the blog garden editor shields the canvas tag and download attributes.

Summary

In general, this is actually a very small function, but we need to use it well. There are a lot of knowledge points involved, this is not just what I mentioned. (For example, the transparency style of canvas is not an image, but a css style, but also learned from the book css secrets ).

Of course, there are still some flaws in this thing, and there are some compatibility problems, but it is good for me to use it.

I also hope that some of the things described above will be helpful to you.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.