HTML5 Canvas實作的一個畫板

阿神
發布: 2016-11-08 14:26:02
原創
1742 人瀏覽過

可通过按钮改变画笔的颜色及大小,还可将画布保存为图片在下面进行显示。

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>DEMO6:自定义画板</title>
</head>
<body>
<canvas id="canvas" width="600" height="300">
    浏览器不支持canvas   <!-- 如果不支持会显示这段文字 -->
</canvas>
<br/>
<button style="width:80px;background-color:yellow;" onclick=&#39;linecolor="yellow";&#39;>YELLOW</button>
<button style="width:80px ;background-color:red;" onclick=&#39;linecolor="red";&#39;>RED</button>
<button style="width:80px ;background-color:blue;" onclick=&#39;linecolor="blue";&#39;>BLUE</button>
<button style="width:80px ;background-color:green;" onclick=&#39;linecolor="green";&#39;>GREEN</button>
<button style="width:80px ;background-color:white;" onclick=&#39;linecolor="white";&#39;>WHITE</button>
<button style="width:80px ;background-color:black;" onclick=&#39;linecolor="black";&#39;>BLACK</button>
<br/>
 
<button style="width: 80px;background-color: white;" onclick="linw=4;">4PX</button>
<button style="width: 80px;background-color: white;" onclick="linw=8;">8PX</button>
<button style="width: 80px;background-color: white;" onclick="linw=16;">16PX</button>
<br/>
 
<button style="width: 80px;background-color: white;" onclick="copyimage();">EXPORT</button>
 
<br/>
<img  src="" id="image_png"    style="max-width:90%" height="300px" alt="HTML5 Canvas實作的一個畫板" >
<br/>
 
<script type="text/javascript">
    var canvas = document.getElementById(&#39;canvas&#39;);  //获取标签
    var ctx = canvas.getContext("2d");  
 
    var fillStyle = "black";
    ctx.fillRect(0,0,600,300);
    var onoff = false;  //按下标记
    var oldx = -10;
    var oldy = -10;
    //设置颜色
    var linecolor = "white";
    var linw = 4;
    canvas.addEventListener("mousemove",draw,true);  //鼠标移动事件
    canvas.addEventListener("mousedown",down,false);  //鼠标按下事件
    canvas.addEventListener("mouseup",up,false);  //鼠标弹起事件
    function down(event){
        onoff = true;
        oldx = event.pageX - 10;
        oldy = event.pageY - 10;
    }
    function up(){
        onoff = false;
    }
    function draw(event){
        if (onoff==true) {
            var newx = event.pageX - 10;
            var newy = event.pageY - 10
            ctx.beginPath();
            ctx.moveTo(oldx,oldy);
            ctx.lineTo(newx,newy);
            ctx.strokeStyle = linecolor;
            ctx.lineWidth = linw;
            ctx.lineCap = "round";
            ctx.stroke();
 
            oldx = newx;
            oldy = newy;
        }
    }
    function copyimage(event)
    {
        var img_png_src = canvas.toDataURL("image/png");  //将画板保存为图片格式的函数
        document.getElementById("image_png").src = img_png_src;
    }
     
    </script> 
</body>
</html>
登入後複製


相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板