
注意部分:
canvas的height和width不能再css中设定,应该在html中设定,否则会影响页面的分辨率。
效果图:
图1:
代码
css:
#canvas{
cursor: crosshair;
}
button{
width: 80px;
}
.yellowBtn{
background-color: yellow;
}
.redBtn{
background-color: red;
}
.blueBtn{
background-color: blue;
}
.greenBtn{
background-color: green;
}
.whiteBtn{
background-color: white;
}
.blackBtn{
background-color:black;
}
页面:
<canvas id="canvas" width="900" height="400">浏览器不支持html5</canvas>
<br>
<button id="yellow" class="yellowBtn" onclick="lineColor='yellow';">YELLOW</button>
<button id="red" class="redBtn" onclick="lineColor='red';">RED</button>
<button id="blue" class="blueBtn" onclick="lineColor='blue';">BLUE</button>
<button id="green" class="greenBtn" onclick="lineColor='green';">GREEN</button>
<button id="white" class="whiteBtn" onclick="lineColor='white';">WHITE</button>
<button id="black" class="blackBtn" onclick="lineColor='black';">BLACK</button>
<br>
<button class="lineWeight4" class="whiteBtn" onclick="lineWeight=2;">2px</button>
<button class="lineWeight4" class="whiteBtn" onclick="lineWeight=4;">4px</button>
<button class="lineWeight8" class="whiteBtn" onclick="lineWeight=8;">8px</button>
<button class="lineWeight12" class="whiteBtn" onclick="lineWeight=12;">12px</button>
js:
<script type="text/javascript">
var canvas = document.getElementById("canvas"); //判断是否支持canvas
if(!canvas || !canvas.getContext){
return false;
} //获得context对象,目前只支持2d
var ctx = canvas.getContext("2d"); //画出画板背景,此处为矩形
ctx.fillStyle = "black";
ctx.fillRect(0, 0, 900, 400); //初始化鼠标是否按下和坐标点位置, true为按下
var mouseState = false,
oldX = -10,
oldY = -10,
lineColor = "white",
lineWeight = 2; //canvas添加鼠标事件, 鼠标移动、鼠标按下和鼠标弹起
if(window.addEventListener){
canvas.addEventListener("mousemove", draw, true);
canvas.addEventListener("mousedown", down, false);
canvas.addEventListener("mouseup", up, false); }else{
canvas.attachEvent("onmousemove", draw);
canvas.attachEvent("onmousedown", down);
canvas.attachEvent("onmouseup", up);
} //鼠标按下,拖动画图
function draw(event){
if(mouseState === true){
var newX = event.clientX - 10;
var newY = event.clientY - 10; ctx.beginPath();
ctx.moveTo(oldX, oldY);
ctx.lineTo(newX, newY); ctx.strokeStyle = lineColor;
ctx.lineWidth = lineWeight;
ctx.lineCap = "round";
ctx.stroke(); oldX = newX;
oldY = newY;
} } function down(event){
mouseState = true;
oldX = event.clientX - 10;
oldY = event.clientY - 10;
} function up(){
mouseState = false;
} </script>
增加导出功能:
使用 canvas.toDataURL("image/png");保存图片,eg:
function exportImage(event){
var imgSrc = canvas.toDataURL("image/png");
document.getElementById("image").src = imgsrc;
}