canvas demo - 放大镜

html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>放大镜</title>
    <style>
        div{
            text-align: center;
        }       
        canvas{
            background-color: white; 
            position: absolute;
        }
        #cv1{
            border:1px solid #000000; 
            z-index: 1;
        }
        #cv2{
            z-index: 2;
            left:0px;
            top:0px;
            border: thin dashed black;
            border-radius: 40px;
            -moz-border-radius:40px;
            -o-border-radius:40px;
            -webkit-border-radius:40px;
            display: none;
            position: relative;
        }
    </style>
</head>
<body>
    <div>
        <h1>放大镜</h1>
        <canvas id = "cv1" width = "720px" height = "500px"></canvas>
        <canvas id = "cv2" width = "100px"  height = "100px"></canvas>
    </div>
    <script src = "myjs1.js"></script>
</body>
</html>

js

var canvas1 = document.getElementById("cv1");
var canvas2 = document.getElementById("cv2");
var ctx = canvas1.getContext('2d');
var image = new Image();

window.onload = function() {
    image.src = "girl.jpg"
    image.onload = function(){
        ctx.drawImage(image,0,0,canvas1.width,canvas1.height);
    }

    canvas1.onmousemove = canvas1_onmouse_move;
    canvas1.onmouseout = canvas1_onmouse_out;
}

function canvas1_onmouse_move(ev) {
    var x,y;
    var drawWidth,drawHeight;
    var ctx2 = canvas2.getContext('2d');
    canvas2.style.display = "inline";
    ctx2.clearRect(0,0,canvas2.width,canvas2.height);

    x = ev.pageX - canvas1.offsetLeft;
    y = ev.pageY - canvas1.offsetTop;

    canvas2.style.left = x+2+"px";
    canvas2.style.top = y+2+"px";

    if (x+100>canvas1.width) {
        drawWidth = canvas1.width -x;
    }else {
        drawWidth = 100;
    }

    if (y+100 > canvas1.height) {
        drawHeight = canvas1.height -y;
    }else{
        drawHeight = 100;
    }

    ctx2.drawImage(image,x,y,drawWidth,drawHeight,0,0,drawWidth,drawHeight);
}
function canvas1_onmouse_out(){
    canvas2.style.display = "none";
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值