DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> Javascript HTML5 Canvas實現的一個畫板
Javascript HTML5 Canvas實現的一個畫板
編輯:關於JavaScript     

本文實例為大家分享了HTML5 Canvas實現的一個畫板代碼,供大家參考,具體內容如下

<!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='linecolor="yellow";'>YELLOW</button>
<button style="width:80px ;background-color:red;" onclick='linecolor="red";'>RED</button>
<button style="width:80px ;background-color:blue;" onclick='linecolor="blue";'>BLUE</button>
<button style="width:80px ;background-color:green;" onclick='linecolor="green";'>GREEN</button>
<button style="width:80px ;background-color:white;" onclick='linecolor="white";'>WHITE</button>
<button style="width:80px ;background-color:black;" onclick='linecolor="black";'>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" width="600px" height="300px">
<br/>
 
<script type="text/javascript">
  var canvas = document.getElementById('canvas'); //獲取標簽
  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>

以上就是本文的全部內容,希望對大家的學習有所幫助。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved