亲宝软件园·资讯

展开

Cavas画板功能 javascript+Canvas实现画板功能

许俊活 人气:0

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>

加载全部内容

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