javaScript简单canvas实现
Posted 如许之秋
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javaScript简单canvas实现相关的知识,希望对你有一定的参考价值。
功能:选择圆形或者矩形,在定义好的画布上作画
代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<div>
<div>
<input type="radio" name="shap" id="circleButton" checked="true">circle</input>
<input type="radio" name="shap" id="rectButton">rectangle</input>
<input type="color"/>
</div>
<canvas id="myCanvas" style=" border:1px solid;" width="800" height="500"></canvas>
</div>
</body>
<script language="javascript">
var shap = 0; //0 is circle; 1 is rectangle
var orignalX, orignalY;//the coordinate of mouse down
var lastX, lastY;//the coordinate of last mouse position
var isMouseDown = false; // flag of mouse pressing down
var circleButton = document.getElementById("circleButton");
var rectButton = document.getElementById("rectButton");
var myCanvas = document.getElementById("myCanvas");
var context = myCanvas.getContext(‘2d‘);
var width = myCanvas.width, height = myCanvas.height;
var data;//storing last canvas‘ content
context.strokeStyle = "red";
context.strokeWidth=1;
function circleButtonClick() {
shap = 0;
}
function rectButtonClick() {
shap = 1;
}
function myCanvasMouseDown(event) {
//event.preventDefault();
if(event.button == 0) {
orignalX = event.offsetX;
orignalY = event.offsetY;
data = context.getImageData(0, 0, width, height);
isMouseDown = true;
}
}
function myCanvasMouseMove(event) {
if (isMouseDown){
//event.preventDefault();
context.clearRect(0,0,width,height);
context.putImageData(data,0,0);
lastX = event.offsetX;
lastY = event.offsetY;
switch(shap){
case 0:
context.beginPath();
context.arc(orignalX+(lastX-orignalX)/2,orignalY+(lastY-orignalY)/2,Math.abs(lastX-orignalX)/2,0,Math.PI * 2,true);
context.stroke();
context.closePath();
break;
case 1:
context.strokeRect(orignalX, orignalY, lastX-orignalX, lastY-orignalY);
break;
}
}
}
function myCanvasMouseUp(event) {
if (isMouseDown){
//event.preventDefault();
context.clearRect(0,0,width,height);
context.putImageData(data,0,0);
lastX = event.offsetX;
lastY = event.offsetY;
switch(shap){
case 0:
context.beginPath();
context.arc(orignalX+(lastX-orignalX)/2,orignalY+(lastY-orignalY)/2,Math.abs(lastX-orignalX)/2,0,Math.PI * 2,true);
context.stroke();
context.closePath();
break;
case 1:
context.strokeRect(orignalX, orignalY, lastX-orignalX, lastY-orignalY);
}
isMouseDown = false;
lastX = null;
lastY = null;
}
}
circleButton.addEventListener("click", circleButtonClick, false);
rectButton.addEventListener("click", rectButtonClick, false);
myCanvas.addEventListener("mousedown", myCanvasMouseDown, false);
myCanvas.addEventListener("mousemove", myCanvasMouseMove, false);
myCanvas.addEventListener("mouseup", myCanvasMouseUp, false);
</script>
<script language="JavaScript">
alert(shap);
</script>
</html>
以上是关于javaScript简单canvas实现的主要内容,如果未能解决你的问题,请参考以下文章