-HTML5 example of character effect in Word

Source: Internet
Author: User

Using HTML5 to achieve word effects in words

Implementation idea: Output text with canvas, then analyze pixels, and output text based on pixel points.

Core code:

?
    var canvas;var ctx;var tex;var blankStr = "  ";//输出空白$(function () {    $("button#bt").click(function () {//绑定按钮单击事件        if ($("canvas#myCanvas").length > 0) {            canvas = $("canvas#myCanvas")[0];            ctx = canvas.getContext("2d");        }        var tex = $("input#inpt").val();//获取输入框文字        if (!tex) tex = "顶";//默认文字为"顶"        if (tex.length > 1) { //只支持一个汉字            alert("亲,少输入点字好吧,我吃不消呢~");            return;        }        var reg = /[\u4E00-\u9FA5]/g;//用正则表达式判断是否为汉字        if (!reg.test(tex)) {            alert("亲,输入一个汉字好吧,其他的我不认识呢~");            return;        }         ctx.fillStyle = "rgba(0,0,0,1)";//绘制底色        ctx.fillRect(20, 20, 40, 40);
?
        ctx.fillStyle = "rgba(255,255,255,1)"//绘制文字        ctx.font = "bolder 40px 宋体";        ctx.textBaseline = ‘top‘;        ctx.fillText(tex, 20, 20);        var panel = $("#panel");//汉字输出区域        panel.html("");//清空历史汉字        for (y = 1; y < 40; y++) {            for (x = 1; x < 40; x++) {                imageData = ctx.getImageData(20 + x, 20 + y, 1, 1);//获取灰度像素值                if (imageData.data[0] >180 ) {    //0为黑,255为白,取180是为了调控精度,确保不同浏览器都能有良好效果                    panel.html(panel.html() + blankStr);                } else {                    panel.html(panel.html() + tex);                }            }            panel.html(panel.html() + "<br>");        }    });    $("button#bt").click();//第一次加载是输出"顶"});

View instance: http://jialiren.sinaapp.com/

-HTML5 example of character effect in Word

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.