亲宝软件园·资讯

展开

javascript+Canvas实现画板功能

许俊活 人气:2

本文着重为大家仔细讲解了javascript+Canvas实现画板功能,文中代码实例讲解的非常细致,希望能够帮助到您,欢迎大家阅读和收藏

CSS样式代码

body,
 html {
 text-align: center;
 padding-top: 20px;
 /*margin: 0;*/
 }

canvas {
 box-shadow: 0 0 10px #333;
 margin: 0 auto;
 /*position: absolute;
 left: 0; 
 border: 1px solid red;*/
}

这是主体代码

<body onload="draw()">
 <canvas id="canvas" width="800" height="600">
 </canvas>
 <script>
 function draw() {
 var canvas = document.getElementById("canvas");
 if (canvas.getContext) {
 var ctx = canvas.getContext('2d');
 //涂鸦
 //添加鼠标按下事件
 canvas.onmousedown=function(e){
  var ev=e||window.event;//兼容性
  var x=ev.clientX-canvas.offsetLeft;
  var y=ev.clientY-canvas.offsetTop;
  
 ctx.strokeStyle='red';
 ctx.lineWidth=10;
  
 ctx.beginPath();
 ctx.moveTo(x,y);

 //onmousemove
 canvas.onmousemove=function(e){
 var ev=e||window.event;//兼容性
 var x=ev.clientX - canvas.offsetLeft;
 var y=ev.clientY - canvas.offsetTop;
 ctx.lineTo(x,y);
 ctx.stroke();
 }
  canvas.onmouseup=function(){
  canvas.onmousemove="";//当鼠标不点击时则不会画画
  
  }
 }
 }
   }
</script>
</body>

加载全部内容

相关教程
猜你喜欢
用户评论