Canvas写字板

基于Canvas制作的写字板demo

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title>写字板</title>
		<script type="text/javascript" src="js/script.js" ></script>
		<style>
			*{
				margin: 0;
				padding: 0;
			}
			#canvas{
				display: block;
				margin:0 auto;
			}
			p{
				margin-top: 10px;
				text-align: justify;
				text-align: center;
				font-weight: bold;
				font-size: 30px;
			}
		</style>
	</head>
	<body>
		<canvas id="canvas">
			此浏览器不支持canvas
		</canvas>
		<p>刷新页面以清空</p>
	</body>
</html>

script.js

var canvasWidth = 600;
var canvasHeight = 600;

window.onload = function(){
	var canvas = document.getElementById("canvas");
	var context = canvas.getContext("2d");
	canvas.width = canvasWidth;
	canvas.height = canvasHeight;
	var isMouseDown = false;
	
	var lastLoc; //储存鼠标上一次的坐标
	var curLoc; //储存鼠标当前坐标
	
	drawGrid(context); //绘制米字格
	
	canvas.onmousedown = function(event){
		event.preventDefault(); //阻止浏览器的默认响应事件
		isMouseDown = true;
		lastLoc = windowToCanvas(canvas,event.clientX,event.clientY);
	}
	canvas.onmouseup = function(event){
		event.preventDefault();
		isMouseDown = false;
	}
	canvas.onmouseout = function(event){
		event.preventDefault();
		isMouseDown = false;
	}
	canvas.onmousemove = function(event){
		event.preventDefault();
		if(isMouseDown == true){
			curLoc = windowToCanvas(canvas,event.clientX,event.clientY);
			
			context.beginPath();
			context.moveTo(lastLoc.x,lastLoc.y);
			context.lineTo(curLoc.x,curLoc.y);
			context.lineWidth = 20;
			context.lineCap = "round";
			context.lineJoin = "round";
			context.strokeStyle = "black";
			context.stroke();
			
			lastLoc = curLoc;
		}
	}
}

//将鼠标在整个页面中的坐标转换成在canvas中的坐标,坐标储存在一个对象中
function windowToCanvas(canvas,x,y){
	var box = canvas.getBoundingClientRect();
	return {x:Math.round(x-box.left),y:Math.round(y-box.top)};
}

function drawGrid(ctx){
	ctx.save();
	ctx.beginPath();
	ctx.moveTo(2,2);
	ctx.lineTo(canvasWidth-2,2);
	ctx.lineTo(canvasWidth-2,canvasHeight-2);
	ctx.lineTo(2,canvasHeight-2);
	ctx.closePath(); //自动封闭图形
	
	ctx.lineWidth = 4;
	ctx.strokeStyle = "red";
	ctx.stroke();
	
	ctx.beginPath();
	ctx.moveTo(0,0);
	ctx.lineTo(canvasWidth,canvasHeight);
	ctx.moveTo(canvasWidth-0,0);
	ctx.lineTo(0,canvasHeight-0);
	ctx.moveTo(canvasWidth/2,0);
	ctx.lineTo(canvasWidth/2,canvasHeight);
	ctx.moveTo(0,canvasHeight/2);
	ctx.lineTo(canvasHeight,canvasHeight/2);
	
	ctx.lineWidth = 1;
	ctx.strokeStyle = "red";
	ctx.stroke();
	ctx.restore();
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值