1. Introduction

After a lot of javascript and CSS3 posts, it’s time to write a canvas. Canvas is a new feature provided by HTML5! In terms of function, it’s a canvas. And then the brush is javascript. Canvas has a wide range of uses, especially for HTML5 games and data visualization. Now Canvas gives me the same feeling as CSS3. It doesn’t have to be too powerful, but it has to be able to use the basics. But in the future, the demand for canvas will definitely be bigger and bigger. Therefore, Canvas is worth learning, and learning well canvas is a good plus. For this post, I am also writing from a canvas beginner’s perspective, and there are many improvements to be made. If you think I can improve, or suggestions, welcome to guide the maze! Code has been uploaded to Github, needed welcome star(downloadImg).

Before you read this article, you need to understand some basics of javascript, and also look at some canvas API (
Canvas – MSN tutorial.
Canvas Beginner Tutorial)

2. Invite card instance

This will happen. After all, sometimes, many invitation cards are the same, just different people are invited. In other words, the whole invitation card is just a different name. Just write a code that generates invitation cards by name!

2-1. Running effect

The HTML code

    <meta charset="utf-8"> < span style = "box-sizing: border-box! Important; word-wrap: break-word! Important;float: left;
            width: 400px;

        .set-option .text {
            width: 200px;
            height: 40px;
            padding-left: 10px;
            border-radius: 4px;
            border: 1px solid #ccc;

        .set-option td {
            padding: 10px 0;

        .set-option td:first-child {
            text-align: right;
            padding-right: 10px;

        .set-option p {
            margin: 0;
            line-height: 16px;

        .check-box {
            width: 16px;
            height: 16px;
            margin: 0;
            vertical-align: top;

        button {
            width: 200px;
            height: 50px;
            border: none;
            color: #fff;
            font-size: 16px;
            cursor: pointer;
            display: block;
            margin: 10px auto;

        button:hover {
            opacity: .9;

        .btn-all {
            background: #f90;

        .btn-save {
            background: #09f;

        .btn-download {
            background: #4CAF50;
    <div class="set-option">< table> <tr> <td> Canvas size </td> <td><inputtype="text" class="text" id="size"/></td> </tr> <td><inputtype="file" id="file"/></td> </tr> <td> user name </td> <inputtype="text" class="text" id="user-name"/> </td> </tr> <td> <inputtype="number" class="text" id="text-option-x"/></br>
                    <p><input type="checkbox" class="check-box" value="1" id="is-center-x"> center < / p > < / td > < / tr > < tr > < td > user name y < / td > < td > < inputtype="number" class="text" id="text-option-y"/></br>
                    <p><input type="checkbox" class="check-box" value="1" id="is-center-y"> center < / p > < / td > < / tr > < tr > < td > user name font size < / td > < td > < inputtype="number" class="text" id="text-size"/></td> </tr> <td><inputtype="text" class="text" id="text-color"/></td> </tr> <td> <select * from * select * from * select * from * select * from * select * from *type="text" class="text" id="img-type">
                        <option value="jpg">jpg</option>
                        <option value="png">png</option>
        <button id="save-image" class="btn-save"<button id="download-img" class="btn-download"</button> <button id="download-all" class="btn-all"</button> <div class="show-canvas">
        <canvas width=200 height=200 id="thecanvas"></canvas>
</html>Copy the code

So think about what you need to change about an invitation card! It’s not hard to see the comparison above! The following attributes need to be changed: the size of the image, the image, the user name, the coordinates of the user name (x,y, whether the x axis is centered,y axis is centered), the size of the user name font, the color of the user name font, and the type of image downloaded.

This gives you the following parameters (you can see that some of the parameters have values, so think of them as defaults)

var option = {
    img: '111.jpg',
    width: 500,
    height: 350,
    fontSize: "20px Microsoft YaHei",
    color: "black",
    text: 'wait',
    imgType: 'jpg',
    x: 30,
    y: 30,
    xCenter: false,
    yCenter: false};Copy the code

Step 2 – (2)

1. Initial results

According to the above parameters, first draw a preliminary effect, the code is basically a writing method, there is no skill

/ / drawingfunction draw(obj) {
    var canvas = document.getElementById("thecanvas"); // Canvas size canvas.width = obj.width; canvas.height = obj.height; Var img = new Image(); img.src = obj.img; var ctx = canvas.getContext("2d"); Var _x = obj.x, _y = obj.y; // Whether to center the displayif (obj.xCenter) {
        _x = obj.width / 2;
    if(obj.yCenter) { _y = obj.height / 2; } // After the image is loaded img.onload =function() {CTX. DrawImage (img, 0, 0); // Set the size of the text ctx.font = obj.fontsize; // Set the color of the text ctx.fillStyle = obj. // Set the text coordinatesif (obj.xCenter) {
            ctx.textAlign = "center"; } // fillText(obj.text, _x, _y); }; } window.onload =function () {

Copy the code

2. Change parameters dynamically

When you see the picture already drawn, the job is actually half finished!

The following is dynamic change parameters! This step is actually quite simple. First, change the size of the canvas

Var size = document.getelementById ();"size");
size.addEventListener("blur".function() {/ / according to the space, to distinguish the high wide var _width = parseInt (size. The value. The replace (/ (^ \ s *) | (\ s * $)/g,"").split(/\s+/)[0]),
        _height = parseInt(size.value.replace(/(^\s*)|(\s*$)/g, "").split(/\s+/)[1]); / / change the parameters width and height of the option. The width = _width | | 100; option.height = _height || 100; // Draw (option); });Copy the code

The above code is set to change the size of the canvas whenever the input field loses focus. Let’s run it and see what it looks like.

Canvas has no hierarchy. If you change the canvas, you have to redraw it. Even if it’s just one pixel per word.

With this done, let’s do the function of selecting pictures!

Var file = document.getelementById ();"file"), imagesFile, imageData;
file.addEventListener('change'.function(e) {imagesFile = e.target. Files [0]; Var reader = new FileReader(); reader.readAsDataURL(imagesFile); // After the image is loaded, reader.onload =function(e) {// set the img attribute of option and draw imageData = this.result; option.img = imageData; draw(option); }});Copy the code

Now I’m going to change the text, the user name is a little bit different, I’m going to separate it by space. If multiple user names are entered, redraw with the first user name. The following code, comment is not written, or the above logic is the same!

Var userName = document.getelementById ();"user-name");
userName.addEventListener("blur".function () {
    var _text = userName.value.replace(/(^\s*)|(\s*$)/g, "").split(/\s+/);
    option.text = _text[0];

Copy the code

Now let’s start with the coordinates of the user name, the code aspect, and also change the properties associated with option

    optionXCenter.addEventListener("change".function () {
        if (optionXCenter.checked) {
            option.xCenter = true;
        else {
            option.xCenter = false; option.x = parseInt(optionX.value); } draw(option); }); Var optionY = document.getelementById ();"text-option-y");
    optionY.value = option.y;
    var optionYCenter = document.getElementById("is-center-y");
    optionY.addEventListener("input".function () {
        if (optionYCenter.checked) {
            option.yCenter = true;
        else {
            option.yCenter = false; option.y = parseInt(optionY.value); } draw(option); }); / / whether the vertical center display optionYCenter. AddEventListener ("change".function () {
        if (optionYCenter.checked) {
            option.yCenter = true;
        else {
            option.yCenter = false;
            option.y = parseInt(optionY.value);
Copy the code

Whether the horizontal center display

Other attributes, font size and color, is basically the same code, run the renderings I do not put!

Var textColor = document.getelementById ();"text-color");
textColor.addEventListener("blur".function () {
    textColor.value === "" ? option.color = "#fff" : option.color = The '#'+ textColor.value; draw(option); }); Var textSize = document.getelementById ();"text-size");
textSize.addEventListener("input".function () {
    textSize.value === "" ? option.fontSize = '20px Microsoft YaHei' : option.fontSize = textSize.value + 'px Microsoft YaHei';
Copy the code

3. Push buttons

Results the preview

This is simply to open a new window and write the image into it

// Preview the imagefunction saveImageInfo() {
    var mycanvas = document.getElementById("thecanvas"); Var image = myCanvas. ToDataURL ()"image/png");
    var w = window.open('about:blank'.'image from canvas'); // Move the image to a new window w.dooument. Write ("<img src='" + image + "' alt='from canvas'/>");
var saveButton = document.getElementById("save-image");
saveButton.addEventListener('click', saveImageInfo);
Copy the code

Download the current image

Download pictures of this, the basic is also written, are some of the memory of things

Var imgType = document.getelementById ();"img-type");
imgType.addEventListener("change".function() { option.imgType=this.value; }); // Download the imagefunctionVar myCanvas = document.getelementById (fileName); var myCanvas = document.getelementByID (fileName);"thecanvas"); Var image = myCanvas. ToDataURL ()"image/" + option.imgType).replace("image/" + option.imgType, "image/octet-stream");
    var save_link = document.createElementNS('http://www.w3.org/1999/xhtml'.'a'); save_link.href = image; // Set the name of the downloaded image save_link.download = fileName +'. '+ option.imgType; Var event = document.createEvent();'MouseEvents');
    event.initMouseEvent('click'.true.false, window, 0, 0, 0, 0, 0, false.false.false.false, 0, null);

Copy the code

Batch download images

This is a little more complicated, but it’s not difficult, so let’s do it step by step!

1. First batch export, so I used space to split the user name here, so now I in option, make a field textAll, all the text collection. All indicates whether to download in batches. The fn property represents the callback function

Var downloadAll = document.getelementById (downloadAll = document.getelementById)"download-all");
downloadAll.addEventListener('click'.function () {
    var _text = userName.value.replace(/(^\s*)|(\s*$)/g, "").split(/\s+/);
    option.textAll = _text;
    option.all = true;
    option.fn = downloadImg;
Copy the code

2. Then modify the draw function, judge whether all draw situation!

function draw(obj) {
    var canvas = document.getElementById("thecanvas"); // Canvas size canvas.width = obj.width; canvas.height = obj.height; Var img = new Image(); img.src = obj.img; var ctx = canvas.getContext("2d"); Var _x = obj.x, _y = obj.y; // Whether to center the displayif (obj.xCenter) {
        _x = obj.width / 2;
    if(obj.yCenter) { _y = obj.height / 2; } // After the image is loaded img.onload =function() {// Whether to print allif(obj.all){// Traverse textAllfor(var i=0; i<obj.textAll.length; Ctx. drawImage(img,0,0); // Set font size ctx.font= obj.fontsize; // Set font color ctx.fillStyle=obj. // Whether to center the displayif(obj.xCenter){
                    ctx.textAlign="center"; } // Draw the text ctx.fillText(obj. TextAll [I], _x,_y); // Whether to call backif(obj.fn){ obj.fn(obj.textAll[i]); } // Finally cancel all batch download defult.all=false;
        else{CTX. DrawImage (img, 0, 0). ctx.font=obj.fontSize; ctx.fillStyle=obj.color;if(obj.xCenter){
                ctx.textAlign="center"; } ctx.fillText(obj.text, _x,_y); }}; }Copy the code

3. Summary

So much for my first article on Canvas introduction. After writing, I also found that I didn’t know much about Canvas! In the example above, knowledge Canvas is a very simple example of getting started. Canvas can achieve a lot of amazing effects if I study deeply. I need to learn more about this in the future. If I find some knowledge worth recording, I will also write articles. Canvas is a very valuable and interesting knowledge to learn. Look forward to more communication and learning with you!

— — — — — — — — — — — — — — — — — — — — — — — — — gorgeous line — — — — — — — — — — — — — — — — — — — — want to know more, pay attention to focus on my WeChat public number: waiting for book cabinet