首页 > 代码库 > Canvas现实画板功能
Canvas现实画板功能
先看图片
HTML
<!doctype html><html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="../src/lib/require.js"></script> <style> input{ width: 50px; border: none; text-align: center; } input[type=range]{ width: 200px; } label{ margin-left: 10px; } input,label{ vertical-align: middle; } canvas{ cursor: default; } </style> </head> <body> <div class="m10"> <canvas id="canvas"></canvas> <p><input type="range" name="" id="num" min=0 max=10 value=2><label for="num">线条大小</label><input type="color" name="" id="color"><label for="color">线条颜色</label></p> </div> <script> requirejs([‘../src/canvas‘], function() {}); </script> </body></html>
Javascript
define([], function() { var getId = function(id) { return typeof id === ‘string‘ ? document.getElementById(id) : id; }; function getPosition(o) { if (!(o && o.nodeName)) { return { left: 0, top: 0 }; } var t = parseInt(o.offsetTop, 10), l = parseInt(o.offsetLeft, 10); while (o.offsetParent) { o = o.offsetParent; t += o.offsetTop; l += o.offsetLeft; } return { left: l, top: t }; } var canvas = getId(‘canvas‘), ct = canvas.getContext(‘2d‘), w = canvas.width = 600, h = canvas.height = 400; var bgl = ct.createRadialGradient(400, 0, 0, 400, 0, 400); bgl.addColorStop(0, ‘red‘); bgl.addColorStop(1, ‘green‘); ct.beginPath(); function draw(ev) { console.log(getPosition(canvas)); var x = ev.clientX - getPosition(canvas).left; var y = ev.clientY - getPosition(canvas).top; ct.lineTo(x, y); ct.stroke(); console.log(x + ‘--‘ + y); } canvas.onmousedown = function(ev) { var x = ev.clientX - getPosition(canvas).left; var y = ev.clientY - getPosition(canvas).top; var size = getId(‘num‘).value; var color = getId(‘color‘).value; ct.save(); ct.strokeStyle = color; ct.lineWidth = size; ct.beginPath(); canvas.onmousemove = draw; }; document.onmouseup = function(ev) { canvas.onmousemove = null; ct.closePath(); //ct.fill(); ct.restore(); };});
Canvas现实画板功能
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。