html5能做出类似验证码似的效果吗

html-css06

html5能做出类似验证码似的效果吗,第1张

你好,可以使用canvas编写出验证码效果,你可以参考

<!DOCTYPE HTML>

<html lang="en">

<meta charset="utf-8">

<script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>

<style>

@charset "utf-8"

/* CSS Document */

body {

    background: url(images/img10.jpg) no-repeat fixed

}

body,form,ul,ol,li,p,h1,h2,h3,h4,h5,h6,dl,dt,dd,table,fieldset,hr,div {

    margin: 0

    padding: 0

}

body,input,select,textarea {

    color: #000

    font: 12px/1.8 "微软雅黑", Arial, Helvetica, sans-serif

}

img {

    border: 0

    vertical-align: middle

}

table {

    width: 100%

    border: 0

    border-collapse: collapse

    border-spacing: 0

}

ul,ol,li {

    list-style-type: none

}

a {

    color: #000

    outline: none

    text-decoration: none

}

a:hover {

    text-decoration: underline

}

.contain {

    width: 500px

    margin: 0 auto

    padding-top: 200px

}

</style>

<body>

    <div class="contain">

        <canvas id="myCanvas" height="300px" width="500px">your browser does not support the canvas tag </canvas>

        <br /> <input type="text">

        <button onClick="pass()">提交</button>

    </div>

</body>

<script type="text/javascript">

    var canvas = $("#myCanvas").get(0)

    var _canvas = $("#myCanvas").get(0).getContext("2d")

    var return_str = ""

    var _ifstart = false

    var _B_x = 0

    var _B_y = 0

    function can_click() {

    }

    function pass() {

        var _val = $(":text:eq(0)").val()

        if (_val == return_str) {

            alert('您通过验证了!')

        } else {

            alert('您输入的验证码不正确!')

        }

        

    }

    function start() {

        try {

            function drawscreen() {

                _canvas.fillStyle = "#ffffaa"

                _canvas.fillRect(0, 0, 500, 300)

                _canvas.strokeStyle = "#000"

                _canvas.strokeRect(5, 5, 490, 290)

            }

            

            function write_text(_str) {

                _canvas.fillStyle = "#000000"

                _canvas.font = "20px _sans"

                _canvas.textBaseline = "top"

                _canvas.fillText(_str, 195, 80)

            }

            

            function getabc() {

                var _str = "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,0,1,2,3,4,5,6,7,8,9"

                var _str_array = _str.split(",")

                return_str = ""

                for (i = 0 i < 4 i++) {

                    var _rnd = Math.floor(Math.random() * _str_array.length)

                    return_str += _str_array[_rnd]

                }

                

            }

            

            drawscreen()

            getabc()

            write_text(return_str)

        } catch (e) {

            alert(e)

        }

    }

    $(document).ready(function(e) {

        start()

    })

</script>

</html>

希望可以帮助到你

验证码一直错误那就是:后台生成的和前台显示的不是同一个验证码,你可以把后台生成的打印出来测试一下。

1:验证码生成代码:

//输入验证码

function verifyimg(){

//验证码做配置

$config = array(

'seKey' => 'ThinkPHP.CN', // 验证码加密密钥

'codeSet' => '2345678abcdefhijkmnpqrstuvwxyzABCDEFGHJKLMNPQRTUVWXY', // 验证码字符集合

'expire'=> 1800, // 验证码过期时间(s)

'useZh' => false,

'useImgBg' => false, // 使用背景图片

'fontSize' => 14, // 验证码字体大小(px)

'useCurve' => true, // 是否画混淆曲线

'useNoise' => true, // 是否添加杂点

'imageH'=> 45, // 验证码图片高度

'imageW'=> 100, // 验证码图片宽度

'length'=> 4,// 验证码位数

'fontttf' => '4.ttf', // 验证码字体,不设置随机获取

'bg'=> array(243, 251, 254), // 背景颜色

'reset' => true, // 验证成功后是否重置

)

$verify=new Verify($config) //实例化Verify类。 空间类元素引入。使用次数多的情况下。

//verify= new \Think\Verify 完全限定名称方式。 使用次数少的情况下。

$verify->entry() //数据验证码。

}

2.下面的是一段验证码显示代码:

<ul>

<li class="user_main_text">验证码: </li>

<li class="user_main_input">

<input class="TxtValidateCodeCssClass" id="captcha" name="captcha" type="text">

验证码输出

<img src="{$smarty.const.__CONTROLLER__}/verifyimg" onclick="this.src='{$smarty.const.__CONTROLLER__}/verifyimg/'+Math.random()" alt="" />

</li>

</ul>

希望对你有帮助。

下面是关键代码,如果剩下的你都搞不懂,我就无语了

JS

<script type="text/javascript" language="javascript">

function reloadcodeOne(){//刷新验证码函数

var verify = document.getElementById('checkCodeImg')

verify.setAttribute('src', 'validateCode?dt=' + Math.random())

}

<script type="text/javascript" >

html

<p>

<label>验证码:</label>

<input class="code" value="请输入验证码" title="请输入验证码" name="rendCode" id="rendCode" onfocus="if (value =='请输入验证码'){value =''}" onblur="if (value ==''){value='请输入验证码'}" type="text" size="6" />

<span><img id="checkCodeImg" src="validateCodeServlet" onclick="javascript:reloadcodeOne()" alt="" width="75" height="24" /></span>

</p>

java代码

package com.zhihui.action.common

import java.awt.Color

import java.awt.Font

import java.awt.Graphics2D

import java.awt.image.BufferedImage

import java.util.Random

import javax.imageio.ImageIO

import javax.servlet.ServletException

import javax.servlet.ServletOutputStream

import javax.servlet.http.HttpServletRequest

import javax.servlet.http.HttpServletResponse

import javax.servlet.http.HttpSession

import org.apache.struts2.ServletActionContext

import com.zhihui.action.base.BaseAction

/**

* <p>

* 校验码控制器

* </p>

*

* @author liurong

* @version ValidateCodeServlet.java,v 0.1 2008-11-20 上午09:22:31 Administrator

* Exp

*/

public class ValidateCodeAction extends BaseAction {

private static final long serialVersionUID = 1L

// 验证码图片的宽度。

private int width = 10

// 验证码图片的高度。

private int height = 5

// 验证码字符个数

private int codeCount = 5

private int x = 0

// 字体高度

private int fontHeight

private int codeY

/*char[] codeSequence = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J',

'K', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'U', 'V', 'W',

'X', 'Y', 'Z', '2', '3', '4', '5', '6', '7', '8', '9' }*/

char[] codeSequence = {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0' }

HttpServletRequest req=ServletActionContext.getRequest()

HttpServletResponse resp=ServletActionContext.getResponse()

public String execute()

throws ServletException, java.io.IOException {

// 宽度

String strWidth = "70"

// 高度

String strHeight = "22"

// 字符个数

String strCodeCount = "5"

width = Integer.parseInt(strWidth)

height = Integer.parseInt(strHeight)

codeCount = Integer.parseInt(strCodeCount)

x = width / (codeCount)

fontHeight = height - 4

codeY = height - 4

// 定义图像buffer

BufferedImage buffImg = new BufferedImage(width, height,

BufferedImage.TYPE_INT_RGB)

Graphics2D g = buffImg.createGraphics()

Random random = new Random()

// 将图像填充为白色

g.setColor(Color.WHITE)

g.fillRect(0, 0, width, height)

Font font = new Font("Fixedsys", Font.PLAIN, fontHeight)

g.setFont(font)

g.setColor(Color.BLACK)

g.drawRect(0, 0, width - 1, height - 1)

g.setColor(Color.BLACK)

for (int i = 0i <15i++) {

int x = random.nextInt(width)

int y = random.nextInt(height)

int xl = random.nextInt(8)

int yl = random.nextInt(8)

g.drawLine(x, y, x + xl, y + yl)

}

// randomCode用于保存随机产生的验证码,以便用户登录后进行验证。

StringBuffer randomCode = new StringBuffer()

int red = 0, green = 0, blue = 0

for (int i = 0i <codeCounti++) {

String strRand = String.valueOf(codeSequence[random.nextInt(codeSequence.length)])

red = 0//random.nextInt(255)

green = 0//random.nextInt(255)

blue = 0//random.nextInt(255)

g.setColor(new Color(red, green, blue))

g.drawString(strRand, (i ) * x, codeY)

randomCode.append(strRand)

}

HttpSession session = req.getSession()

session.setAttribute("validateCode", randomCode.toString())

resp.setHeader("Pragma", "no-cache")

resp.setHeader("Cache-Control", "no-cache")

resp.setDateHeader("Expires", 0)

resp.setContentType("image/jpeg")

ServletOutputStream sos = resp.getOutputStream()

ImageIO.write(buffImg, "jpeg", sos)

sos.close()

return null

}

public int getWidth() {

return width

}

public void setWidth(int width) {

this.width = width

}

public int getHeight() {

return height

}

public void setHeight(int height) {

this.height = height

}

public int getCodeCount() {

return codeCount

}

public void setCodeCount(int codeCount) {

this.codeCount = codeCount

}

public int getX() {

return x

}

public void setX(int x) {

this.x = x

}

public int getFontHeight() {

return fontHeight

}

public void setFontHeight(int fontHeight) {

this.fontHeight = fontHeight

}

public int getCodeY() {

return codeY

}

public void setCodeY(int codeY) {

this.codeY = codeY

}

public char[] getCodeSequence() {

return codeSequence

}

public void setCodeSequence(char[] codeSequence) {

this.codeSequence = codeSequence

}

public HttpServletRequest getReq() {

return req

}

public void setReq(HttpServletRequest req) {

this.req = req

}

public HttpServletResponse getResp() {

return resp

}

public void setResp(HttpServletResponse resp) {

this.resp = resp

}

}