码迷,mamicode.com
首页 > 其他好文 > 详细

绘图工具

时间:2019-09-12 16:27:14      阅读:107      评论:0      收藏:0      [点我收藏+]

标签:sele   tco   change   arc   onclick   fun   mouse   new   body   

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
#myCanvas {
border: 1px solid;
}
.color{
width: 20px;
height: 20px;
display: inline-block;
}
</style>
</head>

<body>
<canvas id="myCanvas" width="500" height="400">
很抱歉,你的浏览器不支持canvas元素
</canvas>
<div>
<button onclick="clearCanvas()" style="float: left;">清除画布</button>
<div class="color" style="" onclick="changeColor(‘red‘)"></div>
<div class="color" style="" onclick="changeColor(‘blue‘)"></div>
<div class="color" style="" onclick="changeColor(‘black‘)"></div>
<div class="color" style="" onclick="changeColor(‘green‘)"></div>
<div class="color" style="" onclick="changeColor(‘yellow‘)"></div>
<div class="color" style="" onclick="changeColor(‘white‘)"></div>
<input type="range" name="" id="range" style="margin-left: 10px;" min="1" max="10" onchange="changeWidth(this.value)"/>
</div>
<script>
var c = document.getElementById(‘myCanvas‘);//获取Canvas对象
let boxSelector = document.getElementsByClassName(‘color‘);
var ctx = c.getContext(‘2d‘);//获取上下文
ctx.lineWidth = 5;//默认的画笔粗细值设置为5
c.onmousedown = function (e) {
var ev = e || window.event;//获取事件对象,主要为了后面获取鼠标点击下的坐标
//移动点至鼠标点击下去的坐标,坐标的获取如下
ctx.beginPath();//开启绘画路径
ctx.moveTo(ev.clientX - c.offsetLeft, ev.clientY - c.offsetTop);////由于canvas元素默认带有margin, 所以需要减去到浏览器边框的距离
document.onmousemove = function () {
var ev = ev || window.event;//获取事件对象, 主要是为了后面获取鼠标移动时的坐标
//移动点至鼠标移动的坐标,坐标的获取如下
ctx.lineTo(ev.clientX - c.offsetLeft, ev.clientY - c.offsetTop);//同样需要减去canvas元素到浏览器边框的距离
ctx.stroke();//将点绘制成线条
};
};
ctx.closePath();//结束绘画路
///当鼠标抬起来时需要停止绘制效果
c.onmouseup = function () {
document.onmousedown = null;//当鼠标抬起来时需要停止绘制效果
document.onmousemove = null;//清空移 动鼠标时的效果
};
function clearCanvas() {
ctx.clearRect(0, 0, c.width, c.height);//清空画布
}
let changeColor = function (str) {
ctx.strokeStyle = str;
for (let i = 0; i < boxSelector.length; i++) {
boxSelector[i].style.boxShadow = ‘‘;
}
event.target.style.boxShadow = ‘0 0 8px black‘;
}
function changeWidth(i) {//接收range控件 传递过来的值,值的范围为1-10
ctx.lineWidth = i;//用这个值来作为画笔的粗细值
}
</script>
</body>
</html>

绘图工具

标签:sele   tco   change   arc   onclick   fun   mouse   new   body   

原文地址:https://www.cnblogs.com/lidaoshao/p/11512371.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!