(编辑:jimmy 日期: 2024/10/31 浏览:2)
本文实例为大家分享了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>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。