如何「撤消」(刪除特定的形狀和重繪剩餘形狀)
演示:http://jsfiddle.net/m1erickson/9pTJ2/
創建一個數組保存所有的形狀定義:
var drawings=[];
添加形狀到陣列:
function addShape(shapename,color){
drawings.push({
shape:shapename,
color:color
});
drawAll();
}
「撤銷」,從數組中刪除一個指定的形狀的所有元素:
function undoShape(shapename){
var i=drawings.length-1;
while(i>=0){
if(drawings[i].shape==shapename){
drawings.splice(i,1);
}
i--;
}
drawAll();
}
這裏是代碼:
[pro ps to @enhzflep以提示方法]
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
#canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
ctx.lineWidth=1;
var shapeWidth=30;
var shapeHeight=30;
var spacer=5;
var drawings=[];
function addShape(shapename,color){
drawings.push({
shape:shapename,
color:color
});
drawAll();
}
function undoShape(shapename){
var i=drawings.length-1;
while(i>=0){
if(drawings[i].shape==shapename){
drawings.splice(i,1);
}
i--;
}
drawAll();
}
function drawAll(){
ctx.clearRect(0,0,canvas.width,canvas.height);
for(var i=0;i<drawings.length;i++){
var drawing=drawings[i];
var x=i*shapeWidth;
var y=50;
switch(drawing.shape){
case "rectangle":
drawRectangle(x,y,drawing.color);
break;
case "circle":
drawCircle(x,y,drawing.color);
break;
}
}
}
function drawContainer(x,y){
ctx.strokeStyle="lightgray";
ctx.strokeRect(x,y,shapeWidth,shapeHeight);
}
function drawRectangle(x,y,color){
drawContainer(x,y);
ctx.fillStyle=color;
ctx.fillRect(x+spacer,y+spacer,shapeWidth-2*spacer,shapeHeight-2*spacer);
}
function drawCircle(x,y,color){
drawContainer(x,y);
ctx.beginPath();
ctx.arc(x+shapeWidth/2,y+shapeHeight/2,shapeWidth/2-spacer,0,Math.PI*2);
ctx.closePath();
ctx.fillStyle=color;
ctx.fill();
}
function randomColor(){
return('#'+Math.floor(Math.random()*16777215).toString(16));
}
$("#rect").click(function(){
addShape("rectangle",randomColor());
});
$("#circle").click(function(){
addShape("circle",randomColor());
});
$("#norect").click(function(){
undoShape("rectangle");
});
$("#nocircle").click(function(){
undoShape("circle");
});
}); // end $(function(){});
</script>
</head>
<body>
<button id="rect">Add Rect</button>
<button id="circle">Add Circle</button>
<button id="norect">Erase Rects</button>
<button id="nocircle">Erase Circles</button>
<canvas id="tools" width=300 height=40></canvas><br>
<canvas id="erasers" width=300 height=40></canvas><br>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>
您可以對每個形狀使用多個上下文。 – whncode
對不起 但你是什麼意思多種語境 – user3188826
你可以請解釋它與dreif javascript代碼 – user3188826