canvas教程

Young杨小杰博客

字号+ 作者:H5之家 来源:H5之家 2017-11-11 18:01 我要评论( )

Html5Canvas打造的画图板,利用鼠标点击移动画图,完成之后可以保存为png格式的图片。

Html5Canvas打造的画图板,利用鼠标点击移动画图,完成之后可以保存为png格式的图片。

canvas画板.png

小杰鼠标画的,见谅,代码如下


<!doctype html> <html> <head> <meta charset="utf-8"> <title>canvas画板</title> </head> <body> <div><canvas></canvas></div> <div> <button>清 空</button> <button>生成图片</button> </div> <img alt='' /> <script type="text/javascript"> var canvas,board,img; canvas = document.getElementById('myCanvas'); img= document.getElementById('img'); canvas.height = 350; canvas.width = 600; board = canvas.getContext('2d'); var mousePress = false; var last = null; function beginDraw(){ mousePress = true; } function drawing(event){ event.preventDefault(); if(!mousePress)return; var xy = pos(event); if(last!=null){ board.beginPath(); board.moveTo(last.x,last.y); board.lineTo(xy.x,xy.y); board.stroke(); } last = xy; } function endDraw(event){ mousePress = false; event.preventDefault(); last = null; } function pos(event){ var x,y; if(isTouch(event)){ x = event.touches[0].pageX; y = event.touches[0].pageY; }else{ x = event.offsetX+event.target.offsetLeft; y = event.offsetY+event.target.offsetTop; } return {x:x,y:y}; } function log(msg){ var log = document.getElementById('log'); var val = log.value; log.value = msg+'n'+val; } function isTouch(event){ var type = event.type; if(type.indexOf('touch')>=0){ return true; }else{ return false; } } function save(){ var dataUrl = canvas.toDataURL(); img.src = dataUrl; } function clean(){ board.clearRect(0,0,canvas.width,canvas.height); } board.lineWidth = 1; board.strokeStyle="#2AA6C0"; canvas.onmousedown = beginDraw; canvas.onmousemove = drawing; canvas.onmouseup = endDraw; canvas.addEventListener('touchstart',beginDraw,false); canvas.addEventListener('touchmove',drawing,false); canvas.addEventListener('touchend',endDraw,false); </script> </body> </html> 原文地址:pyoblog


 

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

相关文章
  • android画图实例源码下载

    android画图实例源码下载

    2017-05-30 17:03

  • Thumbnails

    Thumbnails

    2017-03-23 17:04

  • Android中Canvas绘图基础详解(附源码下载) Android开发中文站

    Android中Canvas绘图基础详解(附源码下载) Android开发中文站

    2017-03-04 13:00

  • Canvas 一个windows画图程序

    Canvas 一个windows画图程序

    2017-01-28 11:01

网友点评
r