canvas 小效果

2017-12-25  本文已影响45人  放飞吧自我

canvas 画板

当在画布中,如果按下鼠标,我们将画布的起始点放在此时鼠标的位置,用到的是moveTo(),然后鼠标移动的时候,用lineTo()画路径,用stroke()来填充路径,移一下画一下,这样就能画出曲线来,当鼠标抬起的时候,我们只需要取消鼠标的动作即可,如果你看过我写的鼠标拖拽效果,是不是感觉很像啊,对的,思路跟拖拽是差不多的,只是具体的内容不一样而已。

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style type="text/css">
            #mycanvas{
                border:2px solid #000000;
            }
        </style>
    </head>
    <body>
        <canvas id="mycanvas" width="500px" height="500px">
            对不起,您的浏览器版本过低,点击<a href="javascript:void(0)"></a>
        </canvas>
        <script type="text/javascript">
            var canvas = document.getElementById("mycanvas");
            var context = canvas.getContext("2d");
            canvas.onmousedown = function(ev){
                var ev = window.event || ev;
                context.beginPath();
                var startX = ev.pageX - canvas.offsetLeft-2;
                var startY = ev.pageY - canvas.offsetTop-2;
                context.moveTo(startX,startY);
                canvas.onmousemove = function(ev){
                    var e = window.event||ev;
                    var endX = e.pageX - canvas.offsetLeft-2;
                    var endY = e.pageY - canvas.offsetTop -2;
                    context.lineTo(endX,endY);
                    context.strokeStyle="red";
                    context.lineWidth = 5;
                    context.stroke();
                }
            }
            canvas.onmouseup = function(){
                canvas.onmousemove = null;
            }
        </script>
    </body>
</html>
C2346D3F-1163-414B-82D0-9A89B945447A.png

国际象棋棋盘

方式一
var Color ="";
        for(var i=0;i<8;i++){
            for(var j=0;j<8;j++){
                if((i%2==0&&j%2==0)||(i%2==1&&j%2==1) ){
                    Color="#000";
                }else{
                    Color = "#FFF"
                }
                context.beginPath();
                context.fillStyle = Color;
                context.fillRect(0+50*i,0+50*j,50,50);
            }
        }
方式二
var color = "#000";
context.beginPath();
for(var i=0;i<800;i+=200){
    for(var j=0;j<800;j+=200){
        context.fillRect(i,j,100,100)
        context.fillRect(i+100,j+100,100,100)
    }
}
4E5D6320-4247-4E0C-94F9-5A22C2E12DA1.png
上一篇下一篇

猜你喜欢

热点阅读