1. 程式人生 > >javascript實現簡單畫布

javascript實現簡單畫布

程式碼塊

程式碼塊語法遵循標準markdown程式碼,例如:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"
> <title>Insert title here</title> <script type="text/javascript" src="jquery.min.js"></script> <style type="text/css"> </style> </head> <body> <canvas style="cursor:pointer" id="canvas" width="600" height="400"></canvas> <input id="color"
type="color" value="#000000"/> <input id="size" type="range" max="100" min="1" value="1"/> <input name="tools" type="radio" value="pen" checked/> <input name="tools" type="radio" value="eraser"/> <button style="cursor:pointer;" id="cc" >clear</button> <script type="text/javascript"
> var c = document.getElementById("canvas"); var cxt=c.getContext("2d"); cxt.strokeStyle = "#111"; cxt.strokeRect(0, 0, 600, 400); $('#cc').click(function(){ context.clearRect(1,1,598,398); clickX = []; clickY = []; clickDrag = []; paint; colorPurple = "#cb3594"; curColor = colorPurple; clickColor = []; curSize = 1; clickSize = []; curTool = 'pen'; }) context = canvas.getContext("2d"); $('#canvas').mousedown(function(e) { //console.log('mousedown'); var mouseX = e.pageX - this.offsetLeft; var mouseY = e.pageY - this.offsetTop; paint = true; addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop); redraw(); }); $('#canvas').mousemove(function(e) { //console.log('mousemove'); if (paint) {//是不是按下了滑鼠 addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop, true); redraw(); } }); $('#canvas').mouseup(function(e) { //console.log('mouseup'); paint = false; }); $('#canvas').mouseleave(function(e) { //console.log('mouseleave'); paint = false; }); var clickX = new Array(); var clickY = new Array(); var clickDrag = new Array(); var paint; var colorPurple = "#cb3594"; var curColor = colorPurple; var clickColor = new Array(); var curSize = 1; var clickSize = []; var curTool = 'pen'; function addClick(x, y, dragging) { //console.log('addClick'); clickX.push(x); clickY.push(y); clickDrag.push(dragging); clickSize.push(curSize); if (curTool == "eraser") { clickColor.push("white"); } else { clickColor.push(curColor); } } function redraw() { //console.log('redraw'); context.lineJoin = "round"; for (var i = 0; i < clickX.length; i++) { context.beginPath(); if (clickDrag[i] && i) { context.moveTo(clickX[i - 1], clickY[i - 1]); } else { context.moveTo(clickX[i] - 1, clickY[i]); } context.lineTo(clickX[i], clickY[i]); context.closePath(); context.strokeStyle = clickColor[i]; context.lineWidth = clickSize[i]; context.stroke(); } } $('#color').change(function(e) { curColor = $(this).attr('value'); }); $('#size').change(function(e) { curSize = $(this).attr('value'); }); $('input[name="tools"]').change(function(e) { curTool = $(this).attr('value'); }); </script> </body> </html>